babylon.max.js 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283
  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. this.setViewport(this._cachedViewport);
  8274. this.wipeCaches();
  8275. };
  8276. // UBOs
  8277. Engine.prototype.createUniformBuffer = function (elements) {
  8278. var ubo = this._gl.createBuffer();
  8279. this.bindUniformBuffer(ubo);
  8280. if (elements instanceof Float32Array) {
  8281. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8282. }
  8283. else {
  8284. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8285. }
  8286. this.bindUniformBuffer(null);
  8287. ubo.references = 1;
  8288. return ubo;
  8289. };
  8290. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8291. var ubo = this._gl.createBuffer();
  8292. this.bindUniformBuffer(ubo);
  8293. if (elements instanceof Float32Array) {
  8294. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8295. }
  8296. else {
  8297. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8298. }
  8299. this.bindUniformBuffer(null);
  8300. ubo.references = 1;
  8301. return ubo;
  8302. };
  8303. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8304. this.bindUniformBuffer(uniformBuffer);
  8305. if (offset === undefined) {
  8306. offset = 0;
  8307. }
  8308. if (count === undefined) {
  8309. if (elements instanceof Float32Array) {
  8310. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8311. }
  8312. else {
  8313. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8314. }
  8315. }
  8316. else {
  8317. if (elements instanceof Float32Array) {
  8318. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8319. }
  8320. else {
  8321. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8322. }
  8323. }
  8324. this.bindUniformBuffer(null);
  8325. };
  8326. // VBOs
  8327. Engine.prototype._resetVertexBufferBinding = function () {
  8328. this.bindArrayBuffer(null);
  8329. this._cachedVertexBuffers = null;
  8330. };
  8331. Engine.prototype.createVertexBuffer = function (vertices) {
  8332. var vbo = this._gl.createBuffer();
  8333. this.bindArrayBuffer(vbo);
  8334. if (vertices instanceof Float32Array) {
  8335. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8336. }
  8337. else {
  8338. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8339. }
  8340. this._resetVertexBufferBinding();
  8341. vbo.references = 1;
  8342. return vbo;
  8343. };
  8344. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8345. var vbo = this._gl.createBuffer();
  8346. this.bindArrayBuffer(vbo);
  8347. if (vertices instanceof Float32Array) {
  8348. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8349. }
  8350. else {
  8351. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8352. }
  8353. this._resetVertexBufferBinding();
  8354. vbo.references = 1;
  8355. return vbo;
  8356. };
  8357. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8358. this.bindArrayBuffer(vertexBuffer);
  8359. if (offset === undefined) {
  8360. offset = 0;
  8361. }
  8362. if (count === undefined) {
  8363. if (vertices instanceof Float32Array) {
  8364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8365. }
  8366. else {
  8367. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8368. }
  8369. }
  8370. else {
  8371. if (vertices instanceof Float32Array) {
  8372. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8373. }
  8374. else {
  8375. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8376. }
  8377. }
  8378. this._resetVertexBufferBinding();
  8379. };
  8380. Engine.prototype._resetIndexBufferBinding = function () {
  8381. this.bindIndexBuffer(null);
  8382. this._cachedIndexBuffer = null;
  8383. };
  8384. Engine.prototype.createIndexBuffer = function (indices) {
  8385. var vbo = this._gl.createBuffer();
  8386. this.bindIndexBuffer(vbo);
  8387. // Check for 32 bits indices
  8388. var arrayBuffer;
  8389. var need32Bits = false;
  8390. if (indices instanceof Uint16Array) {
  8391. arrayBuffer = indices;
  8392. }
  8393. else {
  8394. //check 32 bit support
  8395. if (this._caps.uintIndices) {
  8396. if (indices instanceof Uint32Array) {
  8397. arrayBuffer = indices;
  8398. need32Bits = true;
  8399. }
  8400. else {
  8401. //number[] or Int32Array, check if 32 bit is necessary
  8402. for (var index = 0; index < indices.length; index++) {
  8403. if (indices[index] > 65535) {
  8404. need32Bits = true;
  8405. break;
  8406. }
  8407. }
  8408. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8409. }
  8410. }
  8411. else {
  8412. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8413. arrayBuffer = new Uint16Array(indices);
  8414. }
  8415. }
  8416. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8417. this._resetIndexBufferBinding();
  8418. vbo.references = 1;
  8419. vbo.is32Bits = need32Bits;
  8420. return vbo;
  8421. };
  8422. Engine.prototype.bindArrayBuffer = function (buffer) {
  8423. if (!this._vaoRecordInProgress) {
  8424. this._unBindVertexArrayObject();
  8425. }
  8426. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8427. };
  8428. Engine.prototype.bindUniformBuffer = function (buffer) {
  8429. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8430. };
  8431. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8432. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8433. };
  8434. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8435. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8436. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8437. };
  8438. ;
  8439. Engine.prototype.bindIndexBuffer = function (buffer) {
  8440. if (!this._vaoRecordInProgress) {
  8441. this._unBindVertexArrayObject();
  8442. }
  8443. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8444. };
  8445. Engine.prototype.bindBuffer = function (buffer, target) {
  8446. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8447. this._gl.bindBuffer(target, buffer);
  8448. this._currentBoundBuffer[target] = buffer;
  8449. }
  8450. };
  8451. Engine.prototype.updateArrayBuffer = function (data) {
  8452. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8453. };
  8454. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8455. var pointer = this._currentBufferPointers[indx];
  8456. var changed = false;
  8457. if (!pointer) {
  8458. changed = true;
  8459. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8460. }
  8461. else {
  8462. if (pointer.buffer !== buffer) {
  8463. pointer.buffer = buffer;
  8464. changed = true;
  8465. }
  8466. if (pointer.size !== size) {
  8467. pointer.size = size;
  8468. changed = true;
  8469. }
  8470. if (pointer.type !== type) {
  8471. pointer.type = type;
  8472. changed = true;
  8473. }
  8474. if (pointer.normalized !== normalized) {
  8475. pointer.normalized = normalized;
  8476. changed = true;
  8477. }
  8478. if (pointer.stride !== stride) {
  8479. pointer.stride = stride;
  8480. changed = true;
  8481. }
  8482. if (pointer.offset !== offset) {
  8483. pointer.offset = offset;
  8484. changed = true;
  8485. }
  8486. }
  8487. if (changed || this._vaoRecordInProgress) {
  8488. this.bindArrayBuffer(buffer);
  8489. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8490. }
  8491. };
  8492. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8493. if (indexBuffer == null) {
  8494. return;
  8495. }
  8496. if (this._cachedIndexBuffer !== indexBuffer) {
  8497. this._cachedIndexBuffer = indexBuffer;
  8498. this.bindIndexBuffer(indexBuffer);
  8499. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8500. }
  8501. };
  8502. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8503. var attributes = effect.getAttributesNames();
  8504. if (!this._vaoRecordInProgress) {
  8505. this._unBindVertexArrayObject();
  8506. }
  8507. this.unbindAllAttributes();
  8508. for (var index = 0; index < attributes.length; index++) {
  8509. var order = effect.getAttributeLocation(index);
  8510. if (order >= 0) {
  8511. var vertexBuffer = vertexBuffers[attributes[index]];
  8512. if (!vertexBuffer) {
  8513. continue;
  8514. }
  8515. this._gl.enableVertexAttribArray(order);
  8516. if (!this._vaoRecordInProgress) {
  8517. this._vertexAttribArraysEnabled[order] = true;
  8518. }
  8519. var buffer = vertexBuffer.getBuffer();
  8520. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8521. if (vertexBuffer.getIsInstanced()) {
  8522. this._gl.vertexAttribDivisor(order, 1);
  8523. if (!this._vaoRecordInProgress) {
  8524. this._currentInstanceLocations.push(order);
  8525. this._currentInstanceBuffers.push(buffer);
  8526. }
  8527. }
  8528. }
  8529. }
  8530. };
  8531. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8532. var vao = this._gl.createVertexArray();
  8533. this._vaoRecordInProgress = true;
  8534. this._gl.bindVertexArray(vao);
  8535. this._mustWipeVertexAttributes = true;
  8536. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8537. this.bindIndexBuffer(indexBuffer);
  8538. this._vaoRecordInProgress = false;
  8539. this._gl.bindVertexArray(null);
  8540. return vao;
  8541. };
  8542. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8543. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8544. this._cachedVertexArrayObject = vertexArrayObject;
  8545. this._gl.bindVertexArray(vertexArrayObject);
  8546. this._cachedVertexBuffers = null;
  8547. this._cachedIndexBuffer = null;
  8548. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8549. this._mustWipeVertexAttributes = true;
  8550. }
  8551. };
  8552. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8553. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8554. this._cachedVertexBuffers = vertexBuffer;
  8555. this._cachedEffectForVertexBuffers = effect;
  8556. var attributesCount = effect.getAttributesCount();
  8557. this._unBindVertexArrayObject();
  8558. this.unbindAllAttributes();
  8559. var offset = 0;
  8560. for (var index = 0; index < attributesCount; index++) {
  8561. if (index < vertexDeclaration.length) {
  8562. var order = effect.getAttributeLocation(index);
  8563. if (order >= 0) {
  8564. this._gl.enableVertexAttribArray(order);
  8565. this._vertexAttribArraysEnabled[order] = true;
  8566. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8567. }
  8568. offset += vertexDeclaration[index] * 4;
  8569. }
  8570. }
  8571. }
  8572. this._bindIndexBufferWithCache(indexBuffer);
  8573. };
  8574. Engine.prototype._unBindVertexArrayObject = function () {
  8575. if (!this._cachedVertexArrayObject) {
  8576. return;
  8577. }
  8578. this._cachedVertexArrayObject = null;
  8579. this._gl.bindVertexArray(null);
  8580. };
  8581. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8582. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8583. this._cachedVertexBuffers = vertexBuffers;
  8584. this._cachedEffectForVertexBuffers = effect;
  8585. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8586. }
  8587. this._bindIndexBufferWithCache(indexBuffer);
  8588. };
  8589. Engine.prototype.unbindInstanceAttributes = function () {
  8590. var boundBuffer;
  8591. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8592. var instancesBuffer = this._currentInstanceBuffers[i];
  8593. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8594. boundBuffer = instancesBuffer;
  8595. this.bindArrayBuffer(instancesBuffer);
  8596. }
  8597. var offsetLocation = this._currentInstanceLocations[i];
  8598. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8599. }
  8600. this._currentInstanceBuffers.length = 0;
  8601. this._currentInstanceLocations.length = 0;
  8602. };
  8603. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8604. this._gl.deleteVertexArray(vao);
  8605. };
  8606. Engine.prototype._releaseBuffer = function (buffer) {
  8607. buffer.references--;
  8608. if (buffer.references === 0) {
  8609. this._gl.deleteBuffer(buffer);
  8610. return true;
  8611. }
  8612. return false;
  8613. };
  8614. Engine.prototype.createInstancesBuffer = function (capacity) {
  8615. var buffer = this._gl.createBuffer();
  8616. buffer.capacity = capacity;
  8617. this.bindArrayBuffer(buffer);
  8618. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8619. return buffer;
  8620. };
  8621. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8622. this._gl.deleteBuffer(buffer);
  8623. };
  8624. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8625. this.bindArrayBuffer(instancesBuffer);
  8626. if (data) {
  8627. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8628. }
  8629. if (offsetLocations[0].index !== undefined) {
  8630. var stride = 0;
  8631. for (var i = 0; i < offsetLocations.length; i++) {
  8632. var ai = offsetLocations[i];
  8633. stride += ai.attributeSize * 4;
  8634. }
  8635. for (var i = 0; i < offsetLocations.length; i++) {
  8636. var ai = offsetLocations[i];
  8637. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8638. this._gl.enableVertexAttribArray(ai.index);
  8639. this._vertexAttribArraysEnabled[ai.index] = true;
  8640. }
  8641. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8642. this._gl.vertexAttribDivisor(ai.index, 1);
  8643. this._currentInstanceLocations.push(ai.index);
  8644. this._currentInstanceBuffers.push(instancesBuffer);
  8645. }
  8646. }
  8647. else {
  8648. for (var index = 0; index < 4; index++) {
  8649. var offsetLocation = offsetLocations[index];
  8650. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8651. this._gl.enableVertexAttribArray(offsetLocation);
  8652. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8653. }
  8654. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8655. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8656. this._currentInstanceLocations.push(offsetLocation);
  8657. this._currentInstanceBuffers.push(instancesBuffer);
  8658. }
  8659. }
  8660. };
  8661. Engine.prototype.applyStates = function () {
  8662. this._depthCullingState.apply(this._gl);
  8663. this._stencilState.apply(this._gl);
  8664. this._alphaState.apply(this._gl);
  8665. };
  8666. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8667. // Apply states
  8668. this.applyStates();
  8669. this._drawCalls.addCount(1, false);
  8670. // Render
  8671. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8672. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8673. if (instancesCount) {
  8674. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8675. return;
  8676. }
  8677. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8678. };
  8679. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8680. // Apply states
  8681. this.applyStates();
  8682. this._drawCalls.addCount(1, false);
  8683. if (instancesCount) {
  8684. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8685. return;
  8686. }
  8687. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8688. };
  8689. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8690. // Apply states
  8691. this.applyStates();
  8692. this._drawCalls.addCount(1, false);
  8693. if (instancesCount) {
  8694. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8695. return;
  8696. }
  8697. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8698. };
  8699. // Shaders
  8700. Engine.prototype._releaseEffect = function (effect) {
  8701. if (this._compiledEffects[effect._key]) {
  8702. delete this._compiledEffects[effect._key];
  8703. if (effect.getProgram()) {
  8704. this._gl.deleteProgram(effect.getProgram());
  8705. }
  8706. }
  8707. };
  8708. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8709. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8710. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8711. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8712. if (this._compiledEffects[name]) {
  8713. return this._compiledEffects[name];
  8714. }
  8715. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8716. effect._key = name;
  8717. this._compiledEffects[name] = effect;
  8718. return effect;
  8719. };
  8720. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8721. if (uniformsNames === void 0) { uniformsNames = []; }
  8722. if (samplers === void 0) { samplers = []; }
  8723. if (defines === void 0) { defines = ""; }
  8724. return this.createEffect({
  8725. vertex: "particles",
  8726. fragmentElement: fragmentName
  8727. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8728. };
  8729. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8730. context = context || this._gl;
  8731. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8732. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8733. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8734. var shaderProgram = context.createProgram();
  8735. context.attachShader(shaderProgram, vertexShader);
  8736. context.attachShader(shaderProgram, fragmentShader);
  8737. context.linkProgram(shaderProgram);
  8738. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8739. if (!linked) {
  8740. var error = context.getProgramInfoLog(shaderProgram);
  8741. if (error) {
  8742. throw new Error(error);
  8743. }
  8744. }
  8745. context.deleteShader(vertexShader);
  8746. context.deleteShader(fragmentShader);
  8747. return shaderProgram;
  8748. };
  8749. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8750. var results = [];
  8751. for (var index = 0; index < uniformsNames.length; index++) {
  8752. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8753. }
  8754. return results;
  8755. };
  8756. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8757. var results = [];
  8758. for (var index = 0; index < attributesNames.length; index++) {
  8759. try {
  8760. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8761. }
  8762. catch (e) {
  8763. results.push(-1);
  8764. }
  8765. }
  8766. return results;
  8767. };
  8768. Engine.prototype.enableEffect = function (effect) {
  8769. // Use program
  8770. this.setProgram(effect.getProgram());
  8771. this._currentEffect = effect;
  8772. if (effect.onBind) {
  8773. effect.onBind(effect);
  8774. }
  8775. };
  8776. Engine.prototype.setIntArray = function (uniform, array) {
  8777. if (!uniform)
  8778. return;
  8779. this._gl.uniform1iv(uniform, array);
  8780. };
  8781. Engine.prototype.setIntArray2 = function (uniform, array) {
  8782. if (!uniform || array.length % 2 !== 0)
  8783. return;
  8784. this._gl.uniform2iv(uniform, array);
  8785. };
  8786. Engine.prototype.setIntArray3 = function (uniform, array) {
  8787. if (!uniform || array.length % 3 !== 0)
  8788. return;
  8789. this._gl.uniform3iv(uniform, array);
  8790. };
  8791. Engine.prototype.setIntArray4 = function (uniform, array) {
  8792. if (!uniform || array.length % 4 !== 0)
  8793. return;
  8794. this._gl.uniform4iv(uniform, array);
  8795. };
  8796. Engine.prototype.setFloatArray = function (uniform, array) {
  8797. if (!uniform)
  8798. return;
  8799. this._gl.uniform1fv(uniform, array);
  8800. };
  8801. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8802. if (!uniform || array.length % 2 !== 0)
  8803. return;
  8804. this._gl.uniform2fv(uniform, array);
  8805. };
  8806. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8807. if (!uniform || array.length % 3 !== 0)
  8808. return;
  8809. this._gl.uniform3fv(uniform, array);
  8810. };
  8811. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8812. if (!uniform || array.length % 4 !== 0)
  8813. return;
  8814. this._gl.uniform4fv(uniform, array);
  8815. };
  8816. Engine.prototype.setArray = function (uniform, array) {
  8817. if (!uniform)
  8818. return;
  8819. this._gl.uniform1fv(uniform, array);
  8820. };
  8821. Engine.prototype.setArray2 = function (uniform, array) {
  8822. if (!uniform || array.length % 2 !== 0)
  8823. return;
  8824. this._gl.uniform2fv(uniform, array);
  8825. };
  8826. Engine.prototype.setArray3 = function (uniform, array) {
  8827. if (!uniform || array.length % 3 !== 0)
  8828. return;
  8829. this._gl.uniform3fv(uniform, array);
  8830. };
  8831. Engine.prototype.setArray4 = function (uniform, array) {
  8832. if (!uniform || array.length % 4 !== 0)
  8833. return;
  8834. this._gl.uniform4fv(uniform, array);
  8835. };
  8836. Engine.prototype.setMatrices = function (uniform, matrices) {
  8837. if (!uniform)
  8838. return;
  8839. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8840. };
  8841. Engine.prototype.setMatrix = function (uniform, matrix) {
  8842. if (!uniform)
  8843. return;
  8844. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8845. };
  8846. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8847. if (!uniform)
  8848. return;
  8849. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8850. };
  8851. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8852. if (!uniform)
  8853. return;
  8854. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8855. };
  8856. Engine.prototype.setFloat = function (uniform, value) {
  8857. if (!uniform)
  8858. return;
  8859. this._gl.uniform1f(uniform, value);
  8860. };
  8861. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8862. if (!uniform)
  8863. return;
  8864. this._gl.uniform2f(uniform, x, y);
  8865. };
  8866. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8867. if (!uniform)
  8868. return;
  8869. this._gl.uniform3f(uniform, x, y, z);
  8870. };
  8871. Engine.prototype.setBool = function (uniform, bool) {
  8872. if (!uniform)
  8873. return;
  8874. this._gl.uniform1i(uniform, bool);
  8875. };
  8876. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8877. if (!uniform)
  8878. return;
  8879. this._gl.uniform4f(uniform, x, y, z, w);
  8880. };
  8881. Engine.prototype.setColor3 = function (uniform, color3) {
  8882. if (!uniform)
  8883. return;
  8884. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8885. };
  8886. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8887. if (!uniform)
  8888. return;
  8889. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8890. };
  8891. // States
  8892. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8893. if (zOffset === void 0) { zOffset = 0; }
  8894. if (reverseSide === void 0) { reverseSide = false; }
  8895. // Culling
  8896. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8897. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8898. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8899. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8900. if (culling) {
  8901. this._depthCullingState.cullFace = cullFace;
  8902. this._depthCullingState.cull = true;
  8903. }
  8904. else {
  8905. this._depthCullingState.cull = false;
  8906. }
  8907. }
  8908. // Z offset
  8909. this.setZOffset(zOffset);
  8910. };
  8911. Engine.prototype.setZOffset = function (value) {
  8912. this._depthCullingState.zOffset = value;
  8913. };
  8914. Engine.prototype.getZOffset = function () {
  8915. return this._depthCullingState.zOffset;
  8916. };
  8917. Engine.prototype.setDepthBuffer = function (enable) {
  8918. this._depthCullingState.depthTest = enable;
  8919. };
  8920. Engine.prototype.getDepthWrite = function () {
  8921. return this._depthCullingState.depthMask;
  8922. };
  8923. Engine.prototype.setDepthWrite = function (enable) {
  8924. this._depthCullingState.depthMask = enable;
  8925. };
  8926. Engine.prototype.setColorWrite = function (enable) {
  8927. this._gl.colorMask(enable, enable, enable, enable);
  8928. };
  8929. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8930. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8931. };
  8932. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8933. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8934. if (this._alphaMode === mode) {
  8935. return;
  8936. }
  8937. switch (mode) {
  8938. case Engine.ALPHA_DISABLE:
  8939. this._alphaState.alphaBlend = false;
  8940. break;
  8941. case Engine.ALPHA_PREMULTIPLIED:
  8942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8943. this._alphaState.alphaBlend = true;
  8944. break;
  8945. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8947. this._alphaState.alphaBlend = true;
  8948. break;
  8949. case Engine.ALPHA_COMBINE:
  8950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8951. this._alphaState.alphaBlend = true;
  8952. break;
  8953. case Engine.ALPHA_ONEONE:
  8954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8955. this._alphaState.alphaBlend = true;
  8956. break;
  8957. case Engine.ALPHA_ADD:
  8958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8959. this._alphaState.alphaBlend = true;
  8960. break;
  8961. case Engine.ALPHA_SUBTRACT:
  8962. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8963. this._alphaState.alphaBlend = true;
  8964. break;
  8965. case Engine.ALPHA_MULTIPLY:
  8966. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8967. this._alphaState.alphaBlend = true;
  8968. break;
  8969. case Engine.ALPHA_MAXIMIZED:
  8970. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8971. this._alphaState.alphaBlend = true;
  8972. break;
  8973. case Engine.ALPHA_INTERPOLATE:
  8974. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8975. this._alphaState.alphaBlend = true;
  8976. break;
  8977. case Engine.ALPHA_SCREENMODE:
  8978. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8979. this._alphaState.alphaBlend = true;
  8980. break;
  8981. }
  8982. if (!noDepthWriteChange) {
  8983. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8984. }
  8985. this._alphaMode = mode;
  8986. };
  8987. Engine.prototype.getAlphaMode = function () {
  8988. return this._alphaMode;
  8989. };
  8990. Engine.prototype.setAlphaTesting = function (enable) {
  8991. this._alphaTest = enable;
  8992. };
  8993. Engine.prototype.getAlphaTesting = function () {
  8994. return !!this._alphaTest;
  8995. };
  8996. // Textures
  8997. Engine.prototype.wipeCaches = function (bruteForce) {
  8998. if (this.preventCacheWipeBetweenFrames) {
  8999. return;
  9000. }
  9001. this.resetTextureCache();
  9002. this._currentEffect = null;
  9003. // 6/8/2017: deltakosh: Should not be required anymore.
  9004. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9005. if (bruteForce) {
  9006. this._stencilState.reset();
  9007. this._depthCullingState.reset();
  9008. this.setDepthFunctionToLessOrEqual();
  9009. this._alphaState.reset();
  9010. }
  9011. this._cachedVertexBuffers = null;
  9012. this._cachedIndexBuffer = null;
  9013. this._cachedEffectForVertexBuffers = null;
  9014. this._unBindVertexArrayObject();
  9015. this.bindIndexBuffer(null);
  9016. this.bindArrayBuffer(null);
  9017. };
  9018. /**
  9019. * Set the compressed texture format to use, based on the formats you have, and the formats
  9020. * supported by the hardware / browser.
  9021. *
  9022. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9023. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9024. * to API arguments needed to compressed textures. This puts the burden on the container
  9025. * generator to house the arcane code for determining these for current & future formats.
  9026. *
  9027. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9028. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9029. *
  9030. * Note: The result of this call is not taken into account when a texture is base64.
  9031. *
  9032. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9033. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9034. *
  9035. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9036. * @returns The extension selected.
  9037. */
  9038. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9039. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9040. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9041. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9042. return this._textureFormatInUse = this._texturesSupported[i];
  9043. }
  9044. }
  9045. }
  9046. // actively set format to nothing, to allow this to be called more than once
  9047. // and possibly fail the 2nd time
  9048. return this._textureFormatInUse = null;
  9049. };
  9050. /**
  9051. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9052. * @param {string} urlArg- This contains one of the following:
  9053. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9054. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9055. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9056. *
  9057. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9058. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9059. * @param {Scene} scene- Needed for loading to the correct scene.
  9060. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9061. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9062. * @param {callback} onError- Optional callback to be called upon failure.
  9063. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9064. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9065. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9066. *
  9067. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9068. */
  9069. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9070. var _this = this;
  9071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9072. if (onLoad === void 0) { onLoad = null; }
  9073. if (onError === void 0) { onError = null; }
  9074. if (buffer === void 0) { buffer = null; }
  9075. var texture = fallBack ? fallBack : this._gl.createTexture();
  9076. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9077. var fromData = url.substr(0, 5) === "data:";
  9078. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9079. // establish the file extension, if possible
  9080. var lastDot = url.lastIndexOf('.');
  9081. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9082. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9083. if (isDDS) {
  9084. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9085. }
  9086. var isTGA = (extension === ".tga");
  9087. // determine if a ktx file should be substituted
  9088. var isKTX = false;
  9089. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9090. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9091. isKTX = true;
  9092. }
  9093. scene._addPendingData(texture);
  9094. texture.url = url;
  9095. texture.noMipmap = noMipmap;
  9096. texture.references = 1;
  9097. texture.samplingMode = samplingMode;
  9098. texture.onLoadedCallbacks = [];
  9099. if (onLoad) {
  9100. texture.onLoadedCallbacks.push(onLoad);
  9101. }
  9102. if (!fallBack)
  9103. this._loadedTexturesCache.push(texture);
  9104. var onerror = function () {
  9105. scene._removePendingData(texture);
  9106. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9107. if (isKTX) {
  9108. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9109. }
  9110. else if (onError) {
  9111. onError();
  9112. }
  9113. };
  9114. var callback;
  9115. // processing for non-image formats
  9116. if (isKTX || isTGA || isDDS) {
  9117. if (isKTX) {
  9118. callback = function (data) {
  9119. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9120. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9121. ktx.uploadLevels(_this._gl, !noMipmap);
  9122. }, samplingMode);
  9123. };
  9124. }
  9125. else if (isTGA) {
  9126. callback = function (arrayBuffer) {
  9127. var data = new Uint8Array(arrayBuffer);
  9128. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9129. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9130. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9131. }, samplingMode);
  9132. };
  9133. }
  9134. else if (isDDS) {
  9135. callback = function (data) {
  9136. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9137. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9138. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9139. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9140. }, samplingMode);
  9141. };
  9142. }
  9143. if (!buffer) {
  9144. BABYLON.Tools.LoadFile(url, function (data) {
  9145. callback(data);
  9146. }, null, scene.database, true, onerror);
  9147. }
  9148. else {
  9149. callback(buffer);
  9150. }
  9151. // image format processing
  9152. }
  9153. else {
  9154. var onload = function (img) {
  9155. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9156. var isPot = (img.width === potWidth && img.height === potHeight);
  9157. if (!isPot) {
  9158. _this._prepareWorkingCanvas();
  9159. _this._workingCanvas.width = potWidth;
  9160. _this._workingCanvas.height = potHeight;
  9161. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9162. _this._workingContext.imageSmoothingEnabled = false;
  9163. _this._workingContext.mozImageSmoothingEnabled = false;
  9164. _this._workingContext.oImageSmoothingEnabled = false;
  9165. _this._workingContext.webkitImageSmoothingEnabled = false;
  9166. _this._workingContext.msImageSmoothingEnabled = false;
  9167. }
  9168. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9169. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9170. _this._workingContext.imageSmoothingEnabled = true;
  9171. _this._workingContext.mozImageSmoothingEnabled = true;
  9172. _this._workingContext.oImageSmoothingEnabled = true;
  9173. _this._workingContext.webkitImageSmoothingEnabled = true;
  9174. _this._workingContext.msImageSmoothingEnabled = true;
  9175. }
  9176. }
  9177. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9178. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9179. }, samplingMode);
  9180. };
  9181. if (!fromData || isBase64)
  9182. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9183. else if (buffer instanceof Array || typeof buffer === "string")
  9184. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9185. else
  9186. onload(buffer);
  9187. }
  9188. return texture;
  9189. };
  9190. Engine.prototype._getInternalFormat = function (format) {
  9191. var internalFormat = this._gl.RGBA;
  9192. switch (format) {
  9193. case Engine.TEXTUREFORMAT_ALPHA:
  9194. internalFormat = this._gl.ALPHA;
  9195. break;
  9196. case Engine.TEXTUREFORMAT_LUMINANCE:
  9197. internalFormat = this._gl.LUMINANCE;
  9198. break;
  9199. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9200. internalFormat = this._gl.LUMINANCE_ALPHA;
  9201. break;
  9202. case Engine.TEXTUREFORMAT_RGB:
  9203. internalFormat = this._gl.RGB;
  9204. break;
  9205. case Engine.TEXTUREFORMAT_RGBA:
  9206. internalFormat = this._gl.RGBA;
  9207. break;
  9208. }
  9209. return internalFormat;
  9210. };
  9211. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9212. if (compression === void 0) { compression = null; }
  9213. var internalFormat = this._getInternalFormat(format);
  9214. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9215. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9216. if (texture._width % 4 !== 0) {
  9217. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9218. }
  9219. if (compression) {
  9220. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9221. }
  9222. else {
  9223. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9224. }
  9225. if (texture.generateMipMaps) {
  9226. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9227. }
  9228. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9229. this.resetTextureCache();
  9230. texture.isReady = true;
  9231. };
  9232. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9233. if (compression === void 0) { compression = null; }
  9234. var texture = this._gl.createTexture();
  9235. texture._baseWidth = width;
  9236. texture._baseHeight = height;
  9237. texture._width = width;
  9238. texture._height = height;
  9239. texture.references = 1;
  9240. this.updateRawTexture(texture, data, format, invertY, compression);
  9241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9242. // Filters
  9243. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9244. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9245. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9246. if (generateMipMaps) {
  9247. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9248. }
  9249. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9250. texture.samplingMode = samplingMode;
  9251. this._loadedTexturesCache.push(texture);
  9252. return texture;
  9253. };
  9254. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9255. var texture = this._gl.createTexture();
  9256. texture._baseWidth = width;
  9257. texture._baseHeight = height;
  9258. if (generateMipMaps) {
  9259. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9260. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9261. }
  9262. this.resetTextureCache();
  9263. texture._width = width;
  9264. texture._height = height;
  9265. texture.isReady = false;
  9266. texture.generateMipMaps = generateMipMaps;
  9267. texture.references = 1;
  9268. texture.samplingMode = samplingMode;
  9269. this.updateTextureSamplingMode(samplingMode, texture);
  9270. this._loadedTexturesCache.push(texture);
  9271. return texture;
  9272. };
  9273. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9274. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9275. if (texture.isCube) {
  9276. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9277. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9278. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9279. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9280. }
  9281. else {
  9282. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9283. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9284. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9285. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9286. }
  9287. texture.samplingMode = samplingMode;
  9288. };
  9289. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9290. if (premulAlpha === void 0) { premulAlpha = false; }
  9291. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9292. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9293. if (premulAlpha) {
  9294. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9295. }
  9296. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9297. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9298. if (texture.generateMipMaps) {
  9299. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9300. }
  9301. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9302. if (premulAlpha) {
  9303. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9304. }
  9305. this.resetTextureCache();
  9306. texture.isReady = true;
  9307. };
  9308. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9309. if (texture._isDisabled) {
  9310. return;
  9311. }
  9312. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9313. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9314. try {
  9315. // Testing video texture support
  9316. if (this._videoTextureSupported === undefined) {
  9317. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9318. if (this._gl.getError() !== 0) {
  9319. this._videoTextureSupported = false;
  9320. }
  9321. else {
  9322. this._videoTextureSupported = true;
  9323. }
  9324. }
  9325. // Copy video through the current working canvas if video texture is not supported
  9326. if (!this._videoTextureSupported) {
  9327. if (!texture._workingCanvas) {
  9328. texture._workingCanvas = document.createElement("canvas");
  9329. texture._workingContext = texture._workingCanvas.getContext("2d");
  9330. texture._workingCanvas.width = texture._width;
  9331. texture._workingCanvas.height = texture._height;
  9332. }
  9333. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9334. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9335. }
  9336. else {
  9337. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9338. }
  9339. if (texture.generateMipMaps) {
  9340. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9341. }
  9342. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9343. this.resetTextureCache();
  9344. texture.isReady = true;
  9345. }
  9346. catch (ex) {
  9347. // Something unexpected
  9348. // Let's disable the texture
  9349. texture._isDisabled = true;
  9350. }
  9351. };
  9352. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9353. // old version had a "generateMipMaps" arg instead of options.
  9354. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9355. // in the same way, generateDepthBuffer is defaulted to true
  9356. var generateMipMaps = false;
  9357. var generateDepthBuffer = true;
  9358. var generateStencilBuffer = false;
  9359. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9360. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9361. if (options !== undefined) {
  9362. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9363. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9364. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9365. type = options.type === undefined ? type : options.type;
  9366. if (options.samplingMode !== undefined) {
  9367. samplingMode = options.samplingMode;
  9368. }
  9369. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9370. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9371. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9372. }
  9373. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9374. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9375. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9376. }
  9377. }
  9378. var gl = this._gl;
  9379. var texture = gl.createTexture();
  9380. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9381. var width = size.width || size;
  9382. var height = size.height || size;
  9383. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9384. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9385. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9386. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9387. }
  9388. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9392. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9393. // Create the framebuffer
  9394. var framebuffer = gl.createFramebuffer();
  9395. this.bindUnboundFramebuffer(framebuffer);
  9396. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9397. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9398. if (generateMipMaps) {
  9399. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9400. }
  9401. // Unbind
  9402. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9403. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9404. this.bindUnboundFramebuffer(null);
  9405. texture._framebuffer = framebuffer;
  9406. texture._baseWidth = width;
  9407. texture._baseHeight = height;
  9408. texture._width = width;
  9409. texture._height = height;
  9410. texture.isReady = true;
  9411. texture.samples = 1;
  9412. texture.generateMipMaps = generateMipMaps;
  9413. texture.references = 1;
  9414. texture.samplingMode = samplingMode;
  9415. texture.type = type;
  9416. texture._generateDepthBuffer = generateDepthBuffer;
  9417. texture._generateStencilBuffer = generateStencilBuffer;
  9418. this.resetTextureCache();
  9419. this._loadedTexturesCache.push(texture);
  9420. return texture;
  9421. };
  9422. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9423. var generateMipMaps = false;
  9424. var generateDepthBuffer = true;
  9425. var generateStencilBuffer = false;
  9426. var generateDepthTexture = false;
  9427. var textureCount = 1;
  9428. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9429. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9430. var types = [], samplingModes = [];
  9431. if (options !== undefined) {
  9432. generateMipMaps = options.generateMipMaps;
  9433. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9434. generateStencilBuffer = options.generateStencilBuffer;
  9435. generateDepthTexture = options.generateDepthTexture;
  9436. textureCount = options.textureCount || 1;
  9437. if (options.types) {
  9438. types = options.types;
  9439. }
  9440. if (options.samplingModes) {
  9441. samplingModes = options.samplingModes;
  9442. }
  9443. }
  9444. var gl = this._gl;
  9445. // Create the framebuffer
  9446. var framebuffer = gl.createFramebuffer();
  9447. this.bindUnboundFramebuffer(framebuffer);
  9448. var colorRenderbuffer = gl.createRenderbuffer();
  9449. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9450. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9451. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9452. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9453. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9454. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  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._releaseTexture = function (texture) {
  9964. var gl = this._gl;
  9965. if (texture._framebuffer) {
  9966. gl.deleteFramebuffer(texture._framebuffer);
  9967. }
  9968. if (texture._depthStencilBuffer) {
  9969. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9970. }
  9971. if (texture._MSAAFramebuffer) {
  9972. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9973. }
  9974. if (texture._MSAARenderBuffer) {
  9975. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9976. }
  9977. gl.deleteTexture(texture);
  9978. // Unbind channels
  9979. this.unbindAllTextures();
  9980. var index = this._loadedTexturesCache.indexOf(texture);
  9981. if (index !== -1) {
  9982. this._loadedTexturesCache.splice(index, 1);
  9983. }
  9984. };
  9985. Engine.prototype.setProgram = function (program) {
  9986. if (this._currentProgram !== program) {
  9987. this._gl.useProgram(program);
  9988. this._currentProgram = program;
  9989. }
  9990. };
  9991. Engine.prototype.bindSamplers = function (effect) {
  9992. this.setProgram(effect.getProgram());
  9993. var samplers = effect.getSamplers();
  9994. for (var index = 0; index < samplers.length; index++) {
  9995. var uniform = effect.getUniform(samplers[index]);
  9996. this._gl.uniform1i(uniform, index);
  9997. }
  9998. this._currentEffect = null;
  9999. };
  10000. Engine.prototype.activateTexture = function (texture) {
  10001. if (this._activeTexture !== texture) {
  10002. this._gl.activeTexture(texture);
  10003. this._activeTexture = texture;
  10004. }
  10005. };
  10006. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10007. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10008. this._gl.bindTexture(target, texture);
  10009. this._activeTexturesCache[this._activeTexture] = texture;
  10010. }
  10011. };
  10012. Engine.prototype._bindTexture = function (channel, texture) {
  10013. if (channel < 0) {
  10014. return;
  10015. }
  10016. this.activateTexture(this._gl.TEXTURE0 + channel);
  10017. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10018. };
  10019. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10020. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10021. };
  10022. Engine.prototype.unbindAllTextures = function () {
  10023. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10024. this.activateTexture(this._gl["TEXTURE" + channel]);
  10025. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10026. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10027. }
  10028. };
  10029. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10030. if (channel < 0) {
  10031. return;
  10032. }
  10033. this._gl.uniform1i(uniform, channel);
  10034. this._setTexture(channel, texture);
  10035. };
  10036. Engine.prototype._setTexture = function (channel, texture) {
  10037. // Not ready?
  10038. if (!texture) {
  10039. if (this._activeTexturesCache[channel] != null) {
  10040. this.activateTexture(this._gl["TEXTURE" + channel]);
  10041. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10042. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10043. }
  10044. return;
  10045. }
  10046. // Video
  10047. var alreadyActivated = false;
  10048. if (texture.video) {
  10049. this.activateTexture(this._gl["TEXTURE" + channel]);
  10050. alreadyActivated = true;
  10051. texture.update();
  10052. }
  10053. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10054. texture.delayLoad();
  10055. return;
  10056. }
  10057. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10058. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10059. if (this._activeTexturesCache[channel] === internalTexture) {
  10060. return;
  10061. }
  10062. if (!alreadyActivated) {
  10063. this.activateTexture(this._gl["TEXTURE" + channel]);
  10064. }
  10065. if (internalTexture.isCube) {
  10066. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10067. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10068. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10069. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10070. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10071. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10072. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10073. }
  10074. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10075. }
  10076. else {
  10077. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10078. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10079. internalTexture._cachedWrapU = texture.wrapU;
  10080. switch (texture.wrapU) {
  10081. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10082. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10083. break;
  10084. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10085. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10086. break;
  10087. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10088. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10089. break;
  10090. }
  10091. }
  10092. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10093. internalTexture._cachedWrapV = texture.wrapV;
  10094. switch (texture.wrapV) {
  10095. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10096. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10097. break;
  10098. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10099. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10100. break;
  10101. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10102. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10103. break;
  10104. }
  10105. }
  10106. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10107. }
  10108. };
  10109. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10110. if (channel < 0) {
  10111. return;
  10112. }
  10113. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10114. this._textureUnits = new Int32Array(textures.length);
  10115. }
  10116. for (var i = 0; i < textures.length; i++) {
  10117. this._textureUnits[i] = channel + i;
  10118. }
  10119. this._gl.uniform1iv(uniform, this._textureUnits);
  10120. for (var index = 0; index < textures.length; index++) {
  10121. this._setTexture(channel + index, textures[index]);
  10122. }
  10123. };
  10124. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10125. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10126. var value = texture.anisotropicFilteringLevel;
  10127. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10128. value = 1;
  10129. }
  10130. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10131. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10132. texture._cachedAnisotropicFilteringLevel = value;
  10133. }
  10134. };
  10135. Engine.prototype.readPixels = function (x, y, width, height) {
  10136. var data = new Uint8Array(height * width * 4);
  10137. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10138. return data;
  10139. };
  10140. /**
  10141. * Add an externaly attached data from its key.
  10142. * This method call will fail and return false, if such key already exists.
  10143. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10144. * @param key the unique key that identifies the data
  10145. * @param data the data object to associate to the key for this Engine instance
  10146. * @return true if no such key were already present and the data was added successfully, false otherwise
  10147. */
  10148. Engine.prototype.addExternalData = function (key, data) {
  10149. if (!this._externalData) {
  10150. this._externalData = new BABYLON.StringDictionary();
  10151. }
  10152. return this._externalData.add(key, data);
  10153. };
  10154. /**
  10155. * Get an externaly attached data from its key
  10156. * @param key the unique key that identifies the data
  10157. * @return the associated data, if present (can be null), or undefined if not present
  10158. */
  10159. Engine.prototype.getExternalData = function (key) {
  10160. if (!this._externalData) {
  10161. this._externalData = new BABYLON.StringDictionary();
  10162. }
  10163. return this._externalData.get(key);
  10164. };
  10165. /**
  10166. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10167. * @param key the unique key that identifies the data
  10168. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10169. * @return the associated data, can be null if the factory returned null.
  10170. */
  10171. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10172. if (!this._externalData) {
  10173. this._externalData = new BABYLON.StringDictionary();
  10174. }
  10175. return this._externalData.getOrAddWithFactory(key, factory);
  10176. };
  10177. /**
  10178. * Remove an externaly attached data from the Engine instance
  10179. * @param key the unique key that identifies the data
  10180. * @return true if the data was successfully removed, false if it doesn't exist
  10181. */
  10182. Engine.prototype.removeExternalData = function (key) {
  10183. if (!this._externalData) {
  10184. this._externalData = new BABYLON.StringDictionary();
  10185. }
  10186. return this._externalData.remove(key);
  10187. };
  10188. Engine.prototype.releaseInternalTexture = function (texture) {
  10189. if (!texture) {
  10190. return;
  10191. }
  10192. texture.references--;
  10193. // Final reference ?
  10194. if (texture.references === 0) {
  10195. var texturesCache = this.getLoadedTexturesCache();
  10196. var index = texturesCache.indexOf(texture);
  10197. if (index > -1) {
  10198. texturesCache.splice(index, 1);
  10199. }
  10200. this._releaseTexture(texture);
  10201. }
  10202. };
  10203. Engine.prototype.unbindAllAttributes = function () {
  10204. if (this._mustWipeVertexAttributes) {
  10205. this._mustWipeVertexAttributes = false;
  10206. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10207. this._gl.disableVertexAttribArray(i);
  10208. this._vertexAttribArraysEnabled[i] = false;
  10209. this._currentBufferPointers[i] = null;
  10210. }
  10211. return;
  10212. }
  10213. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10214. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10215. continue;
  10216. }
  10217. this._gl.disableVertexAttribArray(i);
  10218. this._vertexAttribArraysEnabled[i] = false;
  10219. this._currentBufferPointers[i] = null;
  10220. }
  10221. };
  10222. Engine.prototype.releaseEffects = function () {
  10223. for (var name in this._compiledEffects) {
  10224. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10225. }
  10226. this._compiledEffects = {};
  10227. };
  10228. // Dispose
  10229. Engine.prototype.dispose = function () {
  10230. this.hideLoadingUI();
  10231. this.stopRenderLoop();
  10232. // Empty texture
  10233. if (this._emptyTexture) {
  10234. this._releaseTexture(this._emptyTexture);
  10235. this._emptyTexture = null;
  10236. }
  10237. if (this._emptyCubeTexture) {
  10238. this._releaseTexture(this._emptyCubeTexture);
  10239. this._emptyCubeTexture = null;
  10240. }
  10241. // Release scenes
  10242. while (this.scenes.length) {
  10243. this.scenes[0].dispose();
  10244. }
  10245. // Release audio engine
  10246. if (Engine.audioEngine) {
  10247. Engine.audioEngine.dispose();
  10248. }
  10249. // Release effects
  10250. this.releaseEffects();
  10251. // Unbind
  10252. this.unbindAllAttributes();
  10253. this._gl = null;
  10254. //WebVR
  10255. this.disableVR();
  10256. // Events
  10257. window.removeEventListener("blur", this._onBlur);
  10258. window.removeEventListener("focus", this._onFocus);
  10259. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10260. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10261. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10262. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10263. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10264. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10265. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10266. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10267. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10268. // Remove from Instances
  10269. var index = Engine.Instances.indexOf(this);
  10270. if (index >= 0) {
  10271. Engine.Instances.splice(index, 1);
  10272. }
  10273. };
  10274. // Loading screen
  10275. Engine.prototype.displayLoadingUI = function () {
  10276. var loadingScreen = this.loadingScreen;
  10277. if (loadingScreen) {
  10278. loadingScreen.displayLoadingUI();
  10279. }
  10280. };
  10281. Engine.prototype.hideLoadingUI = function () {
  10282. var loadingScreen = this.loadingScreen;
  10283. if (loadingScreen) {
  10284. loadingScreen.hideLoadingUI();
  10285. }
  10286. };
  10287. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10288. get: function () {
  10289. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10290. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10291. return this._loadingScreen;
  10292. },
  10293. set: function (loadingScreen) {
  10294. this._loadingScreen = loadingScreen;
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10300. set: function (text) {
  10301. this.loadingScreen.loadingUIText = text;
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10307. set: function (color) {
  10308. this.loadingScreen.loadingUIBackgroundColor = color;
  10309. },
  10310. enumerable: true,
  10311. configurable: true
  10312. });
  10313. Engine.prototype.attachContextLostEvent = function (callback) {
  10314. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10315. };
  10316. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10317. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10318. };
  10319. Engine.prototype.getVertexShaderSource = function (program) {
  10320. var shaders = this._gl.getAttachedShaders(program);
  10321. return this._gl.getShaderSource(shaders[0]);
  10322. };
  10323. Engine.prototype.getFragmentShaderSource = function (program) {
  10324. var shaders = this._gl.getAttachedShaders(program);
  10325. return this._gl.getShaderSource(shaders[1]);
  10326. };
  10327. // FPS
  10328. Engine.prototype.getFps = function () {
  10329. return this.fps;
  10330. };
  10331. Engine.prototype.getDeltaTime = function () {
  10332. return this.deltaTime;
  10333. };
  10334. Engine.prototype._measureFps = function () {
  10335. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10336. var length = this.previousFramesDuration.length;
  10337. if (length >= 2) {
  10338. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10339. }
  10340. if (length >= this.fpsRange) {
  10341. if (length > this.fpsRange) {
  10342. this.previousFramesDuration.splice(0, 1);
  10343. length = this.previousFramesDuration.length;
  10344. }
  10345. var sum = 0;
  10346. for (var id = 0; id < length - 1; id++) {
  10347. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10348. }
  10349. this.fps = 1000.0 / (sum / (length - 1));
  10350. }
  10351. };
  10352. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10353. if (this._webGLVersion > 1) {
  10354. return this._caps.colorBufferFloat;
  10355. }
  10356. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10357. };
  10358. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10359. if (this._webGLVersion > 1) {
  10360. return this._caps.colorBufferFloat;
  10361. }
  10362. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10363. };
  10364. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10365. Engine.prototype._canRenderToFramebuffer = function (type) {
  10366. var gl = this._gl;
  10367. //clear existing errors
  10368. while (gl.getError() !== gl.NO_ERROR) { }
  10369. var successful = true;
  10370. var texture = gl.createTexture();
  10371. gl.bindTexture(gl.TEXTURE_2D, texture);
  10372. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10375. var fb = gl.createFramebuffer();
  10376. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10377. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10378. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10379. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10380. successful = successful && (gl.getError() === gl.NO_ERROR);
  10381. //try render by clearing frame buffer's color buffer
  10382. if (successful) {
  10383. gl.clear(gl.COLOR_BUFFER_BIT);
  10384. successful = successful && (gl.getError() === gl.NO_ERROR);
  10385. }
  10386. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10387. if (successful) {
  10388. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10389. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10390. var readFormat = gl.RGBA;
  10391. var readType = gl.UNSIGNED_BYTE;
  10392. var buffer = new Uint8Array(4);
  10393. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10394. successful = successful && (gl.getError() === gl.NO_ERROR);
  10395. }
  10396. //clean up
  10397. gl.deleteTexture(texture);
  10398. gl.deleteFramebuffer(fb);
  10399. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10400. //clear accumulated errors
  10401. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10402. return successful;
  10403. };
  10404. Engine.prototype._getWebGLTextureType = function (type) {
  10405. if (type === Engine.TEXTURETYPE_FLOAT) {
  10406. return this._gl.FLOAT;
  10407. }
  10408. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10409. // Add Half Float Constant.
  10410. return Engine.HALF_FLOAT_OES;
  10411. }
  10412. return this._gl.UNSIGNED_BYTE;
  10413. };
  10414. ;
  10415. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10416. if (this._webGLVersion === 1) {
  10417. return this._gl.RGBA;
  10418. }
  10419. if (type === Engine.TEXTURETYPE_FLOAT) {
  10420. return Engine.RGBA32F;
  10421. }
  10422. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10423. return Engine.RGBA16F;
  10424. }
  10425. return this._gl.RGBA;
  10426. };
  10427. ;
  10428. // Statics
  10429. Engine.isSupported = function () {
  10430. try {
  10431. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10432. if (navigator.isCocoonJS) {
  10433. return true;
  10434. }
  10435. var tempcanvas = document.createElement("canvas");
  10436. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10437. return gl != null && !!window.WebGLRenderingContext;
  10438. }
  10439. catch (e) {
  10440. return false;
  10441. }
  10442. };
  10443. return Engine;
  10444. }());
  10445. Engine.Instances = new Array();
  10446. // Const statics
  10447. Engine._ALPHA_DISABLE = 0;
  10448. Engine._ALPHA_ADD = 1;
  10449. Engine._ALPHA_COMBINE = 2;
  10450. Engine._ALPHA_SUBTRACT = 3;
  10451. Engine._ALPHA_MULTIPLY = 4;
  10452. Engine._ALPHA_MAXIMIZED = 5;
  10453. Engine._ALPHA_ONEONE = 6;
  10454. Engine._ALPHA_PREMULTIPLIED = 7;
  10455. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10456. Engine._ALPHA_INTERPOLATE = 9;
  10457. Engine._ALPHA_SCREENMODE = 10;
  10458. Engine._DELAYLOADSTATE_NONE = 0;
  10459. Engine._DELAYLOADSTATE_LOADED = 1;
  10460. Engine._DELAYLOADSTATE_LOADING = 2;
  10461. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10462. Engine._TEXTUREFORMAT_ALPHA = 0;
  10463. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10464. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10465. Engine._TEXTUREFORMAT_RGB = 4;
  10466. Engine._TEXTUREFORMAT_RGBA = 5;
  10467. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10468. Engine._TEXTURETYPE_FLOAT = 1;
  10469. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10470. // Depht or Stencil test Constants.
  10471. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10472. 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.
  10473. 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.
  10474. 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.
  10475. 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.
  10476. 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.
  10477. 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.
  10478. 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.
  10479. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10480. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10481. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10482. // Stencil Actions Constants.
  10483. Engine._KEEP = 0x1E00;
  10484. Engine._REPLACE = 0x1E01;
  10485. Engine._INCR = 0x1E02;
  10486. Engine._DECR = 0x1E03;
  10487. Engine._INVERT = 0x150A;
  10488. Engine._INCR_WRAP = 0x8507;
  10489. Engine._DECR_WRAP = 0x8508;
  10490. // Texture rescaling mode
  10491. Engine._SCALEMODE_FLOOR = 1;
  10492. Engine._SCALEMODE_NEAREST = 2;
  10493. Engine._SCALEMODE_CEILING = 3;
  10494. // Updatable statics so stick with vars here
  10495. Engine.CollisionsEpsilon = 0.001;
  10496. Engine.CodeRepository = "src/";
  10497. Engine.ShadersRepository = "src/Shaders/";
  10498. BABYLON.Engine = Engine;
  10499. })(BABYLON || (BABYLON = {}));
  10500. //# sourceMappingURL=babylon.engine.js.map
  10501. /// <reference path="Tools\babylon.decorators.ts" />
  10502. var BABYLON;
  10503. (function (BABYLON) {
  10504. /**
  10505. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10506. */
  10507. var Node = (function () {
  10508. /**
  10509. * @constructor
  10510. * @param {string} name - the name and id to be given to this node
  10511. * @param {BABYLON.Scene} the scene this node will be added to
  10512. */
  10513. function Node(name, scene) {
  10514. this.state = "";
  10515. this.metadata = null;
  10516. this.doNotSerialize = false;
  10517. this.animations = new Array();
  10518. this._ranges = {};
  10519. this._childrenFlag = -1;
  10520. this._isEnabled = true;
  10521. this._isReady = true;
  10522. this._currentRenderId = -1;
  10523. this._parentRenderId = -1;
  10524. /**
  10525. * An event triggered when the mesh is disposed.
  10526. * @type {BABYLON.Observable}
  10527. */
  10528. this.onDisposeObservable = new BABYLON.Observable();
  10529. this.name = name;
  10530. this.id = name;
  10531. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10532. this._initCache();
  10533. }
  10534. Object.defineProperty(Node.prototype, "parent", {
  10535. get: function () {
  10536. return this._parentNode;
  10537. },
  10538. set: function (parent) {
  10539. if (this._parentNode === parent) {
  10540. return;
  10541. }
  10542. if (this._parentNode) {
  10543. var index = this._parentNode._children.indexOf(this);
  10544. if (index !== -1) {
  10545. this._parentNode._children.splice(index, 1);
  10546. }
  10547. }
  10548. this._parentNode = parent;
  10549. if (this._parentNode) {
  10550. if (!this._parentNode._children) {
  10551. this._parentNode._children = new Array();
  10552. }
  10553. this._parentNode._children.push(this);
  10554. }
  10555. },
  10556. enumerable: true,
  10557. configurable: true
  10558. });
  10559. Node.prototype.getClassName = function () {
  10560. return "Node";
  10561. };
  10562. Object.defineProperty(Node.prototype, "onDispose", {
  10563. set: function (callback) {
  10564. if (this._onDisposeObserver) {
  10565. this.onDisposeObservable.remove(this._onDisposeObserver);
  10566. }
  10567. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10568. },
  10569. enumerable: true,
  10570. configurable: true
  10571. });
  10572. Node.prototype.getScene = function () {
  10573. return this._scene;
  10574. };
  10575. Node.prototype.getEngine = function () {
  10576. return this._scene.getEngine();
  10577. };
  10578. // override it in derived class
  10579. Node.prototype.getWorldMatrix = function () {
  10580. return BABYLON.Matrix.Identity();
  10581. };
  10582. // override it in derived class if you add new variables to the cache
  10583. // and call the parent class method
  10584. Node.prototype._initCache = function () {
  10585. this._cache = {};
  10586. this._cache.parent = undefined;
  10587. };
  10588. Node.prototype.updateCache = function (force) {
  10589. if (!force && this.isSynchronized())
  10590. return;
  10591. this._cache.parent = this.parent;
  10592. this._updateCache();
  10593. };
  10594. // override it in derived class if you add new variables to the cache
  10595. // and call the parent class method if !ignoreParentClass
  10596. Node.prototype._updateCache = function (ignoreParentClass) {
  10597. };
  10598. // override it in derived class if you add new variables to the cache
  10599. Node.prototype._isSynchronized = function () {
  10600. return true;
  10601. };
  10602. Node.prototype._markSyncedWithParent = function () {
  10603. this._parentRenderId = this.parent._currentRenderId;
  10604. };
  10605. Node.prototype.isSynchronizedWithParent = function () {
  10606. if (!this.parent) {
  10607. return true;
  10608. }
  10609. if (this._parentRenderId !== this.parent._currentRenderId) {
  10610. return false;
  10611. }
  10612. return this.parent.isSynchronized();
  10613. };
  10614. Node.prototype.isSynchronized = function (updateCache) {
  10615. var check = this.hasNewParent();
  10616. check = check || !this.isSynchronizedWithParent();
  10617. check = check || !this._isSynchronized();
  10618. if (updateCache)
  10619. this.updateCache(true);
  10620. return !check;
  10621. };
  10622. Node.prototype.hasNewParent = function (update) {
  10623. if (this._cache.parent === this.parent)
  10624. return false;
  10625. if (update)
  10626. this._cache.parent = this.parent;
  10627. return true;
  10628. };
  10629. /**
  10630. * Is this node ready to be used/rendered
  10631. * @return {boolean} is it ready
  10632. */
  10633. Node.prototype.isReady = function () {
  10634. return this._isReady;
  10635. };
  10636. /**
  10637. * Is this node enabled.
  10638. * If the node has a parent and is enabled, the parent will be inspected as well.
  10639. * @return {boolean} whether this node (and its parent) is enabled.
  10640. * @see setEnabled
  10641. */
  10642. Node.prototype.isEnabled = function () {
  10643. if (!this._isEnabled) {
  10644. return false;
  10645. }
  10646. if (this.parent) {
  10647. return this.parent.isEnabled();
  10648. }
  10649. return true;
  10650. };
  10651. /**
  10652. * Set the enabled state of this node.
  10653. * @param {boolean} value - the new enabled state
  10654. * @see isEnabled
  10655. */
  10656. Node.prototype.setEnabled = function (value) {
  10657. this._isEnabled = value;
  10658. };
  10659. /**
  10660. * Is this node a descendant of the given node.
  10661. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10662. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10663. * @see parent
  10664. */
  10665. Node.prototype.isDescendantOf = function (ancestor) {
  10666. if (this.parent) {
  10667. if (this.parent === ancestor) {
  10668. return true;
  10669. }
  10670. return this.parent.isDescendantOf(ancestor);
  10671. }
  10672. return false;
  10673. };
  10674. /**
  10675. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10676. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10677. * @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.
  10678. * @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.
  10679. */
  10680. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10681. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10682. if (!this._children) {
  10683. return;
  10684. }
  10685. for (var index = 0; index < this._children.length; index++) {
  10686. var item = this._children[index];
  10687. if (!predicate || predicate(item)) {
  10688. results.push(item);
  10689. }
  10690. if (!directDescendantsOnly) {
  10691. item._getDescendants(results, false, predicate);
  10692. }
  10693. }
  10694. };
  10695. /**
  10696. * Will return all nodes that have this node as ascendant.
  10697. * @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.
  10698. * @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.
  10699. * @return {BABYLON.Node[]} all children nodes of all types.
  10700. */
  10701. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10702. var results = [];
  10703. this._getDescendants(results, directDescendantsOnly, predicate);
  10704. return results;
  10705. };
  10706. /**
  10707. * Get all child-meshes of this node.
  10708. */
  10709. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10710. var results = [];
  10711. this._getDescendants(results, directDecendantsOnly, function (node) {
  10712. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10713. });
  10714. return results;
  10715. };
  10716. /**
  10717. * Get all direct children of this node.
  10718. */
  10719. Node.prototype.getChildren = function (predicate) {
  10720. return this.getDescendants(true, predicate);
  10721. };
  10722. Node.prototype._setReady = function (state) {
  10723. if (state === this._isReady) {
  10724. return;
  10725. }
  10726. if (!state) {
  10727. this._isReady = false;
  10728. return;
  10729. }
  10730. this._isReady = true;
  10731. if (this.onReady) {
  10732. this.onReady(this);
  10733. }
  10734. };
  10735. Node.prototype.getAnimationByName = function (name) {
  10736. for (var i = 0; i < this.animations.length; i++) {
  10737. var animation = this.animations[i];
  10738. if (animation.name === name) {
  10739. return animation;
  10740. }
  10741. }
  10742. return null;
  10743. };
  10744. Node.prototype.createAnimationRange = function (name, from, to) {
  10745. // check name not already in use
  10746. if (!this._ranges[name]) {
  10747. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10748. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10749. if (this.animations[i]) {
  10750. this.animations[i].createRange(name, from, to);
  10751. }
  10752. }
  10753. }
  10754. };
  10755. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10756. if (deleteFrames === void 0) { deleteFrames = true; }
  10757. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10758. if (this.animations[i]) {
  10759. this.animations[i].deleteRange(name, deleteFrames);
  10760. }
  10761. }
  10762. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10763. };
  10764. Node.prototype.getAnimationRange = function (name) {
  10765. return this._ranges[name];
  10766. };
  10767. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10768. var range = this.getAnimationRange(name);
  10769. if (!range) {
  10770. return null;
  10771. }
  10772. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10773. };
  10774. Node.prototype.serializeAnimationRanges = function () {
  10775. var serializationRanges = [];
  10776. for (var name in this._ranges) {
  10777. var range = {};
  10778. range.name = name;
  10779. range.from = this._ranges[name].from;
  10780. range.to = this._ranges[name].to;
  10781. serializationRanges.push(range);
  10782. }
  10783. return serializationRanges;
  10784. };
  10785. Node.prototype.dispose = function () {
  10786. this.parent = null;
  10787. // Callback
  10788. this.onDisposeObservable.notifyObservers(this);
  10789. this.onDisposeObservable.clear();
  10790. };
  10791. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10792. if (parsedNode.ranges) {
  10793. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10794. var data = parsedNode.ranges[index];
  10795. node.createAnimationRange(data.name, data.from, data.to);
  10796. }
  10797. }
  10798. };
  10799. return Node;
  10800. }());
  10801. __decorate([
  10802. BABYLON.serialize()
  10803. ], Node.prototype, "name", void 0);
  10804. __decorate([
  10805. BABYLON.serialize()
  10806. ], Node.prototype, "id", void 0);
  10807. __decorate([
  10808. BABYLON.serialize()
  10809. ], Node.prototype, "uniqueId", void 0);
  10810. __decorate([
  10811. BABYLON.serialize()
  10812. ], Node.prototype, "state", void 0);
  10813. __decorate([
  10814. BABYLON.serialize()
  10815. ], Node.prototype, "metadata", void 0);
  10816. BABYLON.Node = Node;
  10817. })(BABYLON || (BABYLON = {}));
  10818. //# sourceMappingURL=babylon.node.js.map
  10819. var BABYLON;
  10820. (function (BABYLON) {
  10821. var BoundingSphere = (function () {
  10822. function BoundingSphere(minimum, maximum) {
  10823. this.minimum = minimum;
  10824. this.maximum = maximum;
  10825. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10826. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10827. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10828. this.radius = distance * 0.5;
  10829. this.centerWorld = BABYLON.Vector3.Zero();
  10830. this._update(BABYLON.Matrix.Identity());
  10831. }
  10832. // Methods
  10833. BoundingSphere.prototype._update = function (world) {
  10834. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10835. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10836. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10837. };
  10838. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10839. for (var i = 0; i < 6; i++) {
  10840. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10841. return false;
  10842. }
  10843. return true;
  10844. };
  10845. BoundingSphere.prototype.intersectsPoint = function (point) {
  10846. var x = this.centerWorld.x - point.x;
  10847. var y = this.centerWorld.y - point.y;
  10848. var z = this.centerWorld.z - point.z;
  10849. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10850. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10851. return false;
  10852. return true;
  10853. };
  10854. // Statics
  10855. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10856. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10857. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10858. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10859. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10860. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10861. return false;
  10862. return true;
  10863. };
  10864. return BoundingSphere;
  10865. }());
  10866. BABYLON.BoundingSphere = BoundingSphere;
  10867. })(BABYLON || (BABYLON = {}));
  10868. //# sourceMappingURL=babylon.boundingSphere.js.map
  10869. var BABYLON;
  10870. (function (BABYLON) {
  10871. var BoundingBox = (function () {
  10872. function BoundingBox(minimum, maximum) {
  10873. this.minimum = minimum;
  10874. this.maximum = maximum;
  10875. this.vectors = new Array();
  10876. this.vectorsWorld = new Array();
  10877. // Bounding vectors
  10878. this.vectors.push(this.minimum.clone());
  10879. this.vectors.push(this.maximum.clone());
  10880. this.vectors.push(this.minimum.clone());
  10881. this.vectors[2].x = this.maximum.x;
  10882. this.vectors.push(this.minimum.clone());
  10883. this.vectors[3].y = this.maximum.y;
  10884. this.vectors.push(this.minimum.clone());
  10885. this.vectors[4].z = this.maximum.z;
  10886. this.vectors.push(this.maximum.clone());
  10887. this.vectors[5].z = this.minimum.z;
  10888. this.vectors.push(this.maximum.clone());
  10889. this.vectors[6].x = this.minimum.x;
  10890. this.vectors.push(this.maximum.clone());
  10891. this.vectors[7].y = this.minimum.y;
  10892. // OBB
  10893. this.center = this.maximum.add(this.minimum).scale(0.5);
  10894. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10895. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10896. // World
  10897. for (var index = 0; index < this.vectors.length; index++) {
  10898. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10899. }
  10900. this.minimumWorld = BABYLON.Vector3.Zero();
  10901. this.maximumWorld = BABYLON.Vector3.Zero();
  10902. this.centerWorld = BABYLON.Vector3.Zero();
  10903. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10904. this._update(BABYLON.Matrix.Identity());
  10905. }
  10906. // Methods
  10907. BoundingBox.prototype.getWorldMatrix = function () {
  10908. return this._worldMatrix;
  10909. };
  10910. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10911. this._worldMatrix.copyFrom(matrix);
  10912. return this;
  10913. };
  10914. BoundingBox.prototype._update = function (world) {
  10915. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10916. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10917. for (var index = 0; index < this.vectors.length; index++) {
  10918. var v = this.vectorsWorld[index];
  10919. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10920. if (v.x < this.minimumWorld.x)
  10921. this.minimumWorld.x = v.x;
  10922. if (v.y < this.minimumWorld.y)
  10923. this.minimumWorld.y = v.y;
  10924. if (v.z < this.minimumWorld.z)
  10925. this.minimumWorld.z = v.z;
  10926. if (v.x > this.maximumWorld.x)
  10927. this.maximumWorld.x = v.x;
  10928. if (v.y > this.maximumWorld.y)
  10929. this.maximumWorld.y = v.y;
  10930. if (v.z > this.maximumWorld.z)
  10931. this.maximumWorld.z = v.z;
  10932. }
  10933. // Extend
  10934. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10935. this.extendSizeWorld.scaleInPlace(0.5);
  10936. // OBB
  10937. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10938. this.centerWorld.scaleInPlace(0.5);
  10939. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10940. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10941. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10942. this._worldMatrix = world;
  10943. };
  10944. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10945. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10946. };
  10947. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10948. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10949. };
  10950. BoundingBox.prototype.intersectsPoint = function (point) {
  10951. var delta = -BABYLON.Epsilon;
  10952. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10953. return false;
  10954. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10955. return false;
  10956. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10957. return false;
  10958. return true;
  10959. };
  10960. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10961. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10962. };
  10963. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10964. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10965. return false;
  10966. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10967. return false;
  10968. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10969. return false;
  10970. return true;
  10971. };
  10972. // Statics
  10973. BoundingBox.Intersects = function (box0, box1) {
  10974. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10975. return false;
  10976. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10977. return false;
  10978. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10979. return false;
  10980. return true;
  10981. };
  10982. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10983. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10984. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10985. return (num <= (sphereRadius * sphereRadius));
  10986. };
  10987. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10988. for (var p = 0; p < 6; p++) {
  10989. for (var i = 0; i < 8; i++) {
  10990. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10991. return false;
  10992. }
  10993. }
  10994. }
  10995. return true;
  10996. };
  10997. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10998. for (var p = 0; p < 6; p++) {
  10999. var inCount = 8;
  11000. for (var i = 0; i < 8; i++) {
  11001. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11002. --inCount;
  11003. }
  11004. else {
  11005. break;
  11006. }
  11007. }
  11008. if (inCount === 0)
  11009. return false;
  11010. }
  11011. return true;
  11012. };
  11013. return BoundingBox;
  11014. }());
  11015. BABYLON.BoundingBox = BoundingBox;
  11016. })(BABYLON || (BABYLON = {}));
  11017. //# sourceMappingURL=babylon.boundingBox.js.map
  11018. var BABYLON;
  11019. (function (BABYLON) {
  11020. var computeBoxExtents = function (axis, box) {
  11021. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11022. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11023. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11024. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11025. var r = r0 + r1 + r2;
  11026. return {
  11027. min: p - r,
  11028. max: p + r
  11029. };
  11030. };
  11031. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11032. var axisOverlap = function (axis, box0, box1) {
  11033. var result0 = computeBoxExtents(axis, box0);
  11034. var result1 = computeBoxExtents(axis, box1);
  11035. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11036. };
  11037. var BoundingInfo = (function () {
  11038. function BoundingInfo(minimum, maximum) {
  11039. this.minimum = minimum;
  11040. this.maximum = maximum;
  11041. this._isLocked = false;
  11042. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11043. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11044. }
  11045. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11046. get: function () {
  11047. return this._isLocked;
  11048. },
  11049. set: function (value) {
  11050. this._isLocked = value;
  11051. },
  11052. enumerable: true,
  11053. configurable: true
  11054. });
  11055. // Methods
  11056. BoundingInfo.prototype.update = function (world) {
  11057. if (this._isLocked) {
  11058. return;
  11059. }
  11060. this.boundingBox._update(world);
  11061. this.boundingSphere._update(world);
  11062. };
  11063. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11064. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11065. return false;
  11066. return this.boundingBox.isInFrustum(frustumPlanes);
  11067. };
  11068. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11069. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11070. };
  11071. BoundingInfo.prototype._checkCollision = function (collider) {
  11072. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11073. };
  11074. BoundingInfo.prototype.intersectsPoint = function (point) {
  11075. if (!this.boundingSphere.centerWorld) {
  11076. return false;
  11077. }
  11078. if (!this.boundingSphere.intersectsPoint(point)) {
  11079. return false;
  11080. }
  11081. if (!this.boundingBox.intersectsPoint(point)) {
  11082. return false;
  11083. }
  11084. return true;
  11085. };
  11086. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11087. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11088. return false;
  11089. }
  11090. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11091. return false;
  11092. }
  11093. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11094. return false;
  11095. }
  11096. if (!precise) {
  11097. return true;
  11098. }
  11099. var box0 = this.boundingBox;
  11100. var box1 = boundingInfo.boundingBox;
  11101. if (!axisOverlap(box0.directions[0], box0, box1))
  11102. return false;
  11103. if (!axisOverlap(box0.directions[1], box0, box1))
  11104. return false;
  11105. if (!axisOverlap(box0.directions[2], box0, box1))
  11106. return false;
  11107. if (!axisOverlap(box1.directions[0], box0, box1))
  11108. return false;
  11109. if (!axisOverlap(box1.directions[1], box0, box1))
  11110. return false;
  11111. if (!axisOverlap(box1.directions[2], box0, box1))
  11112. return false;
  11113. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11114. return false;
  11115. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11116. return false;
  11117. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11118. return false;
  11119. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11120. return false;
  11121. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11122. return false;
  11123. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11124. return false;
  11125. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11126. return false;
  11127. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11128. return false;
  11129. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11130. return false;
  11131. return true;
  11132. };
  11133. return BoundingInfo;
  11134. }());
  11135. BABYLON.BoundingInfo = BoundingInfo;
  11136. })(BABYLON || (BABYLON = {}));
  11137. //# sourceMappingURL=babylon.boundingInfo.js.map
  11138. var BABYLON;
  11139. (function (BABYLON) {
  11140. var AbstractMesh = (function (_super) {
  11141. __extends(AbstractMesh, _super);
  11142. // Constructor
  11143. function AbstractMesh(name, scene) {
  11144. var _this = _super.call(this, name, scene) || this;
  11145. _this._facetNb = 0; // facet number
  11146. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11147. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11148. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11149. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11150. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11151. _this._subDiv = {
  11152. max: 1,
  11153. X: 1,
  11154. Y: 1,
  11155. Z: 1
  11156. };
  11157. // Events
  11158. /**
  11159. * An event triggered when this mesh collides with another one
  11160. * @type {BABYLON.Observable}
  11161. */
  11162. _this.onCollideObservable = new BABYLON.Observable();
  11163. /**
  11164. * An event triggered when the collision's position changes
  11165. * @type {BABYLON.Observable}
  11166. */
  11167. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11168. /**
  11169. * An event triggered after the world matrix is updated
  11170. * @type {BABYLON.Observable}
  11171. */
  11172. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11173. // Properties
  11174. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11175. _this.position = BABYLON.Vector3.Zero();
  11176. _this._rotation = BABYLON.Vector3.Zero();
  11177. _this._scaling = BABYLON.Vector3.One();
  11178. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11179. _this.visibility = 1.0;
  11180. _this.alphaIndex = Number.MAX_VALUE;
  11181. _this.infiniteDistance = false;
  11182. _this.isVisible = true;
  11183. _this.isPickable = true;
  11184. _this.showBoundingBox = false;
  11185. _this.showSubMeshesBoundingBox = false;
  11186. _this.isBlocker = false;
  11187. _this.renderingGroupId = 0;
  11188. _this._receiveShadows = false;
  11189. _this.renderOutline = false;
  11190. _this.outlineColor = BABYLON.Color3.Red();
  11191. _this.outlineWidth = 0.02;
  11192. _this.renderOverlay = false;
  11193. _this.overlayColor = BABYLON.Color3.Red();
  11194. _this.overlayAlpha = 0.5;
  11195. _this._hasVertexAlpha = false;
  11196. _this._useVertexColors = true;
  11197. _this._computeBonesUsingShaders = true;
  11198. _this._numBoneInfluencers = 4;
  11199. _this._applyFog = true;
  11200. _this.scalingDeterminant = 1;
  11201. _this.useOctreeForRenderingSelection = true;
  11202. _this.useOctreeForPicking = true;
  11203. _this.useOctreeForCollisions = true;
  11204. _this.layerMask = 0x0FFFFFFF;
  11205. /**
  11206. * True if the mesh must be rendered in any case.
  11207. */
  11208. _this.alwaysSelectAsActiveMesh = false;
  11209. // Collisions
  11210. _this._checkCollisions = false;
  11211. _this._collisionMask = -1;
  11212. _this._collisionGroup = -1;
  11213. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11214. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11215. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11216. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11217. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11218. // Edges
  11219. _this.edgesWidth = 1;
  11220. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11221. // Cache
  11222. _this._localWorld = BABYLON.Matrix.Zero();
  11223. _this._worldMatrix = BABYLON.Matrix.Zero();
  11224. _this._absolutePosition = BABYLON.Vector3.Zero();
  11225. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11226. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11227. _this._isDirty = false;
  11228. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11229. _this._isDisposed = false;
  11230. _this._renderId = 0;
  11231. _this._intersectionsInProgress = new Array();
  11232. _this._isWorldMatrixFrozen = false;
  11233. _this._unIndexed = false;
  11234. _this._lightSources = new Array();
  11235. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11236. if (collidedMesh === void 0) { collidedMesh = null; }
  11237. //TODO move this to the collision coordinator!
  11238. if (_this.getScene().workerCollisions)
  11239. newPosition.multiplyInPlace(_this._collider.radius);
  11240. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11241. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11242. _this.position.addInPlace(_this._diffPositionForCollisions);
  11243. }
  11244. if (collidedMesh) {
  11245. _this.onCollideObservable.notifyObservers(collidedMesh);
  11246. }
  11247. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11248. };
  11249. _this.getScene().addMesh(_this);
  11250. _this._resyncLightSources();
  11251. return _this;
  11252. }
  11253. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11254. get: function () {
  11255. return AbstractMesh._BILLBOARDMODE_NONE;
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11261. get: function () {
  11262. return AbstractMesh._BILLBOARDMODE_X;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11268. get: function () {
  11269. return AbstractMesh._BILLBOARDMODE_Y;
  11270. },
  11271. enumerable: true,
  11272. configurable: true
  11273. });
  11274. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11275. get: function () {
  11276. return AbstractMesh._BILLBOARDMODE_Z;
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11282. get: function () {
  11283. return AbstractMesh._BILLBOARDMODE_ALL;
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11289. /**
  11290. * Read-only : the number of facets in the mesh
  11291. */
  11292. get: function () {
  11293. return this._facetNb;
  11294. },
  11295. enumerable: true,
  11296. configurable: true
  11297. });
  11298. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11299. /**
  11300. * The number (integer) of subdivisions per axis in the partioning space
  11301. */
  11302. get: function () {
  11303. return this._partitioningSubdivisions;
  11304. },
  11305. set: function (nb) {
  11306. this._partitioningSubdivisions = nb;
  11307. },
  11308. enumerable: true,
  11309. configurable: true
  11310. });
  11311. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11312. /**
  11313. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11314. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11315. */
  11316. get: function () {
  11317. return this._partitioningBBoxRatio;
  11318. },
  11319. set: function (ratio) {
  11320. this._partitioningBBoxRatio = ratio;
  11321. },
  11322. enumerable: true,
  11323. configurable: true
  11324. });
  11325. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11326. /**
  11327. * Read-only boolean : is the feature facetData enabled ?
  11328. */
  11329. get: function () {
  11330. return this._facetDataEnabled;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11336. set: function (callback) {
  11337. if (this._onCollideObserver) {
  11338. this.onCollideObservable.remove(this._onCollideObserver);
  11339. }
  11340. this._onCollideObserver = this.onCollideObservable.add(callback);
  11341. },
  11342. enumerable: true,
  11343. configurable: true
  11344. });
  11345. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11346. set: function (callback) {
  11347. if (this._onCollisionPositionChangeObserver) {
  11348. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11349. }
  11350. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11351. },
  11352. enumerable: true,
  11353. configurable: true
  11354. });
  11355. Object.defineProperty(AbstractMesh.prototype, "material", {
  11356. get: function () {
  11357. return this._material;
  11358. },
  11359. set: function (value) {
  11360. if (this._material === value) {
  11361. return;
  11362. }
  11363. this._material = value;
  11364. if (!this.subMeshes) {
  11365. return;
  11366. }
  11367. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11368. var subMesh = _a[_i];
  11369. subMesh.setEffect(null);
  11370. }
  11371. },
  11372. enumerable: true,
  11373. configurable: true
  11374. });
  11375. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11376. get: function () {
  11377. return this._receiveShadows;
  11378. },
  11379. set: function (value) {
  11380. if (this._receiveShadows === value) {
  11381. return;
  11382. }
  11383. this._receiveShadows = value;
  11384. this._markSubMeshesAsLightDirty();
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11390. get: function () {
  11391. return this._hasVertexAlpha;
  11392. },
  11393. set: function (value) {
  11394. if (this._hasVertexAlpha === value) {
  11395. return;
  11396. }
  11397. this._hasVertexAlpha = value;
  11398. this._markSubMeshesAsAttributesDirty();
  11399. },
  11400. enumerable: true,
  11401. configurable: true
  11402. });
  11403. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11404. get: function () {
  11405. return this._useVertexColors;
  11406. },
  11407. set: function (value) {
  11408. if (this._useVertexColors === value) {
  11409. return;
  11410. }
  11411. this._useVertexColors = value;
  11412. this._markSubMeshesAsAttributesDirty();
  11413. },
  11414. enumerable: true,
  11415. configurable: true
  11416. });
  11417. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11418. get: function () {
  11419. return this._computeBonesUsingShaders;
  11420. },
  11421. set: function (value) {
  11422. if (this._computeBonesUsingShaders === value) {
  11423. return;
  11424. }
  11425. this._computeBonesUsingShaders = value;
  11426. this._markSubMeshesAsAttributesDirty();
  11427. },
  11428. enumerable: true,
  11429. configurable: true
  11430. });
  11431. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11432. get: function () {
  11433. return this._numBoneInfluencers;
  11434. },
  11435. set: function (value) {
  11436. if (this._numBoneInfluencers === value) {
  11437. return;
  11438. }
  11439. this._numBoneInfluencers = value;
  11440. this._markSubMeshesAsAttributesDirty();
  11441. },
  11442. enumerable: true,
  11443. configurable: true
  11444. });
  11445. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11446. get: function () {
  11447. return this._applyFog;
  11448. },
  11449. set: function (value) {
  11450. if (this._applyFog === value) {
  11451. return;
  11452. }
  11453. this._applyFog = value;
  11454. this._markSubMeshesAsMiscDirty();
  11455. },
  11456. enumerable: true,
  11457. configurable: true
  11458. });
  11459. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11460. get: function () {
  11461. return this._collisionMask;
  11462. },
  11463. set: function (mask) {
  11464. this._collisionMask = !isNaN(mask) ? mask : -1;
  11465. },
  11466. enumerable: true,
  11467. configurable: true
  11468. });
  11469. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11470. get: function () {
  11471. return this._collisionGroup;
  11472. },
  11473. set: function (mask) {
  11474. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11475. },
  11476. enumerable: true,
  11477. configurable: true
  11478. });
  11479. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11480. get: function () {
  11481. return null;
  11482. },
  11483. enumerable: true,
  11484. configurable: true
  11485. });
  11486. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11487. get: function () {
  11488. return this._skeleton;
  11489. },
  11490. set: function (value) {
  11491. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11492. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11493. }
  11494. if (value && value.needInitialSkinMatrix) {
  11495. value._registerMeshWithPoseMatrix(this);
  11496. }
  11497. this._skeleton = value;
  11498. if (!this._skeleton) {
  11499. this._bonesTransformMatrices = null;
  11500. }
  11501. this._markSubMeshesAsAttributesDirty();
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. /**
  11507. * Returns the string "AbstractMesh"
  11508. */
  11509. AbstractMesh.prototype.getClassName = function () {
  11510. return "AbstractMesh";
  11511. };
  11512. /**
  11513. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11514. */
  11515. AbstractMesh.prototype.toString = function (fullDetails) {
  11516. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11517. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11518. if (this._skeleton) {
  11519. ret += ", skeleton: " + this._skeleton.name;
  11520. }
  11521. if (fullDetails) {
  11522. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11523. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11524. }
  11525. return ret;
  11526. };
  11527. AbstractMesh.prototype._resyncLightSources = function () {
  11528. this._lightSources.length = 0;
  11529. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11530. var light = _a[_i];
  11531. if (!light.isEnabled()) {
  11532. continue;
  11533. }
  11534. if (light.canAffectMesh(this)) {
  11535. this._lightSources.push(light);
  11536. }
  11537. }
  11538. this._markSubMeshesAsLightDirty();
  11539. };
  11540. AbstractMesh.prototype._resyncLighSource = function (light) {
  11541. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11542. var index = this._lightSources.indexOf(light);
  11543. if (index === -1) {
  11544. if (!isIn) {
  11545. return;
  11546. }
  11547. this._lightSources.push(light);
  11548. }
  11549. else {
  11550. if (isIn) {
  11551. return;
  11552. }
  11553. this._lightSources.splice(index, 1);
  11554. }
  11555. this._markSubMeshesAsLightDirty();
  11556. };
  11557. AbstractMesh.prototype._removeLightSource = function (light) {
  11558. var index = this._lightSources.indexOf(light);
  11559. if (index === -1) {
  11560. return;
  11561. }
  11562. this._lightSources.splice(index, 1);
  11563. };
  11564. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11565. if (!this.subMeshes) {
  11566. return;
  11567. }
  11568. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11569. var subMesh = _a[_i];
  11570. if (subMesh._materialDefines) {
  11571. func(subMesh._materialDefines);
  11572. }
  11573. }
  11574. };
  11575. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11576. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11577. };
  11578. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11579. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11580. };
  11581. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11582. if (!this.subMeshes) {
  11583. return;
  11584. }
  11585. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11586. var subMesh = _a[_i];
  11587. var material = subMesh.getMaterial();
  11588. if (material) {
  11589. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11590. }
  11591. }
  11592. };
  11593. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11594. /**
  11595. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11596. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11597. * Default : (0.0, 0.0, 0.0)
  11598. */
  11599. get: function () {
  11600. return this._rotation;
  11601. },
  11602. set: function (newRotation) {
  11603. this._rotation = newRotation;
  11604. },
  11605. enumerable: true,
  11606. configurable: true
  11607. });
  11608. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11609. /**
  11610. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11611. * Default : (1.0, 1.0, 1.0)
  11612. */
  11613. get: function () {
  11614. return this._scaling;
  11615. },
  11616. set: function (newScaling) {
  11617. this._scaling = newScaling;
  11618. if (this.physicsImpostor) {
  11619. this.physicsImpostor.forceUpdate();
  11620. }
  11621. },
  11622. enumerable: true,
  11623. configurable: true
  11624. });
  11625. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11626. /**
  11627. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11628. * It's null by default.
  11629. * 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)
  11630. */
  11631. get: function () {
  11632. return this._rotationQuaternion;
  11633. },
  11634. set: function (quaternion) {
  11635. this._rotationQuaternion = quaternion;
  11636. //reset the rotation vector.
  11637. if (quaternion && this.rotation.length()) {
  11638. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11639. }
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. // Methods
  11645. /**
  11646. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11647. * Returns the AbstractMesh.
  11648. */
  11649. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11650. this._poseMatrix.copyFrom(matrix);
  11651. return this;
  11652. };
  11653. /**
  11654. * Returns the mesh Pose matrix.
  11655. * Returned object : Matrix
  11656. */
  11657. AbstractMesh.prototype.getPoseMatrix = function () {
  11658. return this._poseMatrix;
  11659. };
  11660. /**
  11661. * Disables the mesh edger rendering mode.
  11662. * Returns the AbstractMesh.
  11663. */
  11664. AbstractMesh.prototype.disableEdgesRendering = function () {
  11665. if (this._edgesRenderer !== undefined) {
  11666. this._edgesRenderer.dispose();
  11667. this._edgesRenderer = undefined;
  11668. }
  11669. return this;
  11670. };
  11671. /**
  11672. * Enables the edge rendering mode on the mesh.
  11673. * This mode makes the mesh edges visible.
  11674. * Returns the AbstractMesh.
  11675. */
  11676. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11677. if (epsilon === void 0) { epsilon = 0.95; }
  11678. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11679. this.disableEdgesRendering();
  11680. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11681. return this;
  11682. };
  11683. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11684. /**
  11685. * Returns true if the mesh is blocked. Used by the class Mesh.
  11686. * Returns the boolean `false` by default.
  11687. */
  11688. get: function () {
  11689. return false;
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. /**
  11695. * Returns the mesh itself by default, used by the class Mesh.
  11696. * Returned type : AbstractMesh
  11697. */
  11698. AbstractMesh.prototype.getLOD = function (camera) {
  11699. return this;
  11700. };
  11701. /**
  11702. * Returns 0 by default, used by the class Mesh.
  11703. * Returns an integer.
  11704. */
  11705. AbstractMesh.prototype.getTotalVertices = function () {
  11706. return 0;
  11707. };
  11708. /**
  11709. * Returns null by default, used by the class Mesh.
  11710. * Returned type : integer array
  11711. */
  11712. AbstractMesh.prototype.getIndices = function () {
  11713. return null;
  11714. };
  11715. /**
  11716. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11717. * Returned type : float array or Float32Array
  11718. */
  11719. AbstractMesh.prototype.getVerticesData = function (kind) {
  11720. return null;
  11721. };
  11722. /**
  11723. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11724. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11725. * The `data` are either a numeric array either a Float32Array.
  11726. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11727. * 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).
  11728. * Note that a new underlying VertexBuffer object is created each call.
  11729. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11730. *
  11731. * Possible `kind` values :
  11732. * - BABYLON.VertexBuffer.PositionKind
  11733. * - BABYLON.VertexBuffer.UVKind
  11734. * - BABYLON.VertexBuffer.UV2Kind
  11735. * - BABYLON.VertexBuffer.UV3Kind
  11736. * - BABYLON.VertexBuffer.UV4Kind
  11737. * - BABYLON.VertexBuffer.UV5Kind
  11738. * - BABYLON.VertexBuffer.UV6Kind
  11739. * - BABYLON.VertexBuffer.ColorKind
  11740. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11741. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11742. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11743. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11744. *
  11745. * Returns the Mesh.
  11746. */
  11747. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11748. return null;
  11749. };
  11750. /**
  11751. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11752. * If the mesh has no geometry, it is simply returned as it is.
  11753. * The `data` are either a numeric array either a Float32Array.
  11754. * No new underlying VertexBuffer object is created.
  11755. * 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.
  11756. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11757. *
  11758. * Possible `kind` values :
  11759. * - BABYLON.VertexBuffer.PositionKind
  11760. * - BABYLON.VertexBuffer.UVKind
  11761. * - BABYLON.VertexBuffer.UV2Kind
  11762. * - BABYLON.VertexBuffer.UV3Kind
  11763. * - BABYLON.VertexBuffer.UV4Kind
  11764. * - BABYLON.VertexBuffer.UV5Kind
  11765. * - BABYLON.VertexBuffer.UV6Kind
  11766. * - BABYLON.VertexBuffer.ColorKind
  11767. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11768. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11769. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11770. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11771. *
  11772. * Returns the Mesh.
  11773. */
  11774. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11775. return null;
  11776. };
  11777. /**
  11778. * Sets the mesh indices.
  11779. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11780. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11781. * This method creates a new index buffer each call.
  11782. * Returns the Mesh.
  11783. */
  11784. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11785. return null;
  11786. };
  11787. /** Returns false by default, used by the class Mesh.
  11788. * Returns a boolean
  11789. */
  11790. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11791. return false;
  11792. };
  11793. /**
  11794. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11795. * Returns a BoundingInfo
  11796. */
  11797. AbstractMesh.prototype.getBoundingInfo = function () {
  11798. if (this._masterMesh) {
  11799. return this._masterMesh.getBoundingInfo();
  11800. }
  11801. if (!this._boundingInfo) {
  11802. this._updateBoundingInfo();
  11803. }
  11804. return this._boundingInfo;
  11805. };
  11806. /**
  11807. * Sets a mesh new object BoundingInfo.
  11808. * Returns the AbstractMesh.
  11809. */
  11810. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11811. this._boundingInfo = boundingInfo;
  11812. return this;
  11813. };
  11814. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11815. get: function () {
  11816. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. AbstractMesh.prototype._preActivate = function () {
  11822. };
  11823. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11824. };
  11825. AbstractMesh.prototype._activate = function (renderId) {
  11826. this._renderId = renderId;
  11827. };
  11828. /**
  11829. * Returns the last update of the World matrix
  11830. * Returns a Matrix.
  11831. */
  11832. AbstractMesh.prototype.getWorldMatrix = function () {
  11833. if (this._masterMesh) {
  11834. return this._masterMesh.getWorldMatrix();
  11835. }
  11836. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11837. this.computeWorldMatrix();
  11838. }
  11839. return this._worldMatrix;
  11840. };
  11841. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11842. /**
  11843. * Returns directly the last state of the mesh World matrix.
  11844. * A Matrix is returned.
  11845. */
  11846. get: function () {
  11847. return this._worldMatrix;
  11848. },
  11849. enumerable: true,
  11850. configurable: true
  11851. });
  11852. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11853. /**
  11854. * Returns the current mesh absolute position.
  11855. * Retuns a Vector3.
  11856. */
  11857. get: function () {
  11858. return this._absolutePosition;
  11859. },
  11860. enumerable: true,
  11861. configurable: true
  11862. });
  11863. /**
  11864. * Prevents the World matrix to be computed any longer.
  11865. * Returns the AbstractMesh.
  11866. */
  11867. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11868. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11869. this.computeWorldMatrix(true);
  11870. this._isWorldMatrixFrozen = true;
  11871. return this;
  11872. };
  11873. /**
  11874. * Allows back the World matrix computation.
  11875. * Returns the AbstractMesh.
  11876. */
  11877. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11878. this._isWorldMatrixFrozen = false;
  11879. this.computeWorldMatrix(true);
  11880. return this;
  11881. };
  11882. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11883. /**
  11884. * True if the World matrix has been frozen.
  11885. * Returns a boolean.
  11886. */
  11887. get: function () {
  11888. return this._isWorldMatrixFrozen;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. /**
  11894. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11895. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11896. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11897. * The passed axis is also normalized.
  11898. * Returns the AbstractMesh.
  11899. */
  11900. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11901. axis.normalize();
  11902. if (!this.rotationQuaternion) {
  11903. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11904. this.rotation = BABYLON.Vector3.Zero();
  11905. }
  11906. var rotationQuaternion;
  11907. if (!space || space === BABYLON.Space.LOCAL) {
  11908. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11909. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11910. }
  11911. else {
  11912. if (this.parent) {
  11913. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11914. invertParentWorldMatrix.invert();
  11915. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11916. }
  11917. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11918. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11919. }
  11920. return this;
  11921. };
  11922. /**
  11923. * Translates the mesh along the axis vector for the passed distance in the given space.
  11924. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11925. * Returns the AbstractMesh.
  11926. */
  11927. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11928. var displacementVector = axis.scale(distance);
  11929. if (!space || space === BABYLON.Space.LOCAL) {
  11930. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11931. this.setPositionWithLocalVector(tempV3);
  11932. }
  11933. else {
  11934. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11935. }
  11936. return this;
  11937. };
  11938. /**
  11939. * Adds a rotation step to the mesh current rotation.
  11940. * x, y, z are Euler angles expressed in radians.
  11941. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11942. * This means this rotation is made in the mesh local space only.
  11943. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11944. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11945. * ```javascript
  11946. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11947. * ```
  11948. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11949. * 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.
  11950. * Returns the AbstractMesh.
  11951. */
  11952. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11953. var rotationQuaternion;
  11954. if (this.rotationQuaternion) {
  11955. rotationQuaternion = this.rotationQuaternion;
  11956. }
  11957. else {
  11958. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11959. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11960. }
  11961. var accumulation = BABYLON.Tmp.Quaternion[0];
  11962. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11963. rotationQuaternion.multiplyInPlace(accumulation);
  11964. if (!this.rotationQuaternion) {
  11965. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11966. }
  11967. return this;
  11968. };
  11969. /**
  11970. * Retuns the mesh absolute position in the World.
  11971. * Returns a Vector3.
  11972. */
  11973. AbstractMesh.prototype.getAbsolutePosition = function () {
  11974. this.computeWorldMatrix();
  11975. return this._absolutePosition;
  11976. };
  11977. /**
  11978. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11979. * Returns the AbstractMesh.
  11980. */
  11981. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11982. if (!absolutePosition) {
  11983. return;
  11984. }
  11985. var absolutePositionX;
  11986. var absolutePositionY;
  11987. var absolutePositionZ;
  11988. if (absolutePosition.x === undefined) {
  11989. if (arguments.length < 3) {
  11990. return;
  11991. }
  11992. absolutePositionX = arguments[0];
  11993. absolutePositionY = arguments[1];
  11994. absolutePositionZ = arguments[2];
  11995. }
  11996. else {
  11997. absolutePositionX = absolutePosition.x;
  11998. absolutePositionY = absolutePosition.y;
  11999. absolutePositionZ = absolutePosition.z;
  12000. }
  12001. if (this.parent) {
  12002. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12003. invertParentWorldMatrix.invert();
  12004. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12005. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12006. }
  12007. else {
  12008. this.position.x = absolutePositionX;
  12009. this.position.y = absolutePositionY;
  12010. this.position.z = absolutePositionZ;
  12011. }
  12012. return this;
  12013. };
  12014. // ================================== Point of View Movement =================================
  12015. /**
  12016. * Perform relative position change from the point of view of behind the front of the mesh.
  12017. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12018. * Supports definition of mesh facing forward or backward.
  12019. * @param {number} amountRight
  12020. * @param {number} amountUp
  12021. * @param {number} amountForward
  12022. *
  12023. * Returns the AbstractMesh.
  12024. */
  12025. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12026. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12027. return this;
  12028. };
  12029. /**
  12030. * Calculate relative position change from the point of view of behind the front of the mesh.
  12031. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12032. * Supports definition of mesh facing forward or backward.
  12033. * @param {number} amountRight
  12034. * @param {number} amountUp
  12035. * @param {number} amountForward
  12036. *
  12037. * Returns a new Vector3.
  12038. */
  12039. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12040. var rotMatrix = new BABYLON.Matrix();
  12041. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12042. rotQuaternion.toRotationMatrix(rotMatrix);
  12043. var translationDelta = BABYLON.Vector3.Zero();
  12044. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12046. return translationDelta;
  12047. };
  12048. // ================================== Point of View Rotation =================================
  12049. /**
  12050. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12051. * Supports definition of mesh facing forward or backward.
  12052. * @param {number} flipBack
  12053. * @param {number} twirlClockwise
  12054. * @param {number} tiltRight
  12055. *
  12056. * Returns the AbstractMesh.
  12057. */
  12058. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12059. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12060. return this;
  12061. };
  12062. /**
  12063. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12064. * Supports definition of mesh facing forward or backward.
  12065. * @param {number} flipBack
  12066. * @param {number} twirlClockwise
  12067. * @param {number} tiltRight
  12068. *
  12069. * Returns a new Vector3.
  12070. */
  12071. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12072. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12073. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12074. };
  12075. /**
  12076. * Sets a new pivot matrix to the mesh.
  12077. * Returns the AbstractMesh.
  12078. */
  12079. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12080. this._pivotMatrix = matrix;
  12081. this._cache.pivotMatrixUpdated = true;
  12082. return this;
  12083. };
  12084. /**
  12085. * Returns the mesh pivot matrix.
  12086. * Default : Identity.
  12087. * A Matrix is returned.
  12088. */
  12089. AbstractMesh.prototype.getPivotMatrix = function () {
  12090. return this._pivotMatrix;
  12091. };
  12092. AbstractMesh.prototype._isSynchronized = function () {
  12093. if (this._isDirty) {
  12094. return false;
  12095. }
  12096. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12097. return false;
  12098. if (this._cache.pivotMatrixUpdated) {
  12099. return false;
  12100. }
  12101. if (this.infiniteDistance) {
  12102. return false;
  12103. }
  12104. if (!this._cache.position.equals(this.position))
  12105. return false;
  12106. if (this.rotationQuaternion) {
  12107. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12108. return false;
  12109. }
  12110. if (!this._cache.rotation.equals(this.rotation))
  12111. return false;
  12112. if (!this._cache.scaling.equals(this.scaling))
  12113. return false;
  12114. return true;
  12115. };
  12116. AbstractMesh.prototype._initCache = function () {
  12117. _super.prototype._initCache.call(this);
  12118. this._cache.localMatrixUpdated = false;
  12119. this._cache.position = BABYLON.Vector3.Zero();
  12120. this._cache.scaling = BABYLON.Vector3.Zero();
  12121. this._cache.rotation = BABYLON.Vector3.Zero();
  12122. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12123. this._cache.billboardMode = -1;
  12124. };
  12125. AbstractMesh.prototype.markAsDirty = function (property) {
  12126. if (property === "rotation") {
  12127. this.rotationQuaternion = null;
  12128. }
  12129. this._currentRenderId = Number.MAX_VALUE;
  12130. this._isDirty = true;
  12131. return this;
  12132. };
  12133. /**
  12134. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12135. * Returns the AbstractMesh.
  12136. */
  12137. AbstractMesh.prototype._updateBoundingInfo = function () {
  12138. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12139. this._boundingInfo.update(this.worldMatrixFromCache);
  12140. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12141. return this;
  12142. };
  12143. /**
  12144. * Update a mesh's children BoundingInfo objects only.
  12145. * Returns the AbstractMesh.
  12146. */
  12147. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12148. if (!this.subMeshes) {
  12149. return;
  12150. }
  12151. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12152. var subMesh = this.subMeshes[subIndex];
  12153. if (!subMesh.IsGlobal) {
  12154. subMesh.updateBoundingInfo(matrix);
  12155. }
  12156. }
  12157. return this;
  12158. };
  12159. /**
  12160. * Computes the mesh World matrix and returns it.
  12161. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12162. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12163. * If the parameter `force`is set to `true`, the actual computation is done.
  12164. * Returns the mesh World Matrix.
  12165. */
  12166. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12167. if (this._isWorldMatrixFrozen) {
  12168. return this._worldMatrix;
  12169. }
  12170. if (!force && this.isSynchronized(true)) {
  12171. this._currentRenderId = this.getScene().getRenderId();
  12172. return this._worldMatrix;
  12173. }
  12174. this._cache.position.copyFrom(this.position);
  12175. this._cache.scaling.copyFrom(this.scaling);
  12176. this._cache.pivotMatrixUpdated = false;
  12177. this._cache.billboardMode = this.billboardMode;
  12178. this._currentRenderId = this.getScene().getRenderId();
  12179. this._isDirty = false;
  12180. // Scaling
  12181. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12182. // Rotation
  12183. //rotate, if quaternion is set and rotation was used
  12184. if (this.rotationQuaternion) {
  12185. var len = this.rotation.length();
  12186. if (len) {
  12187. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12188. this.rotation.copyFromFloats(0, 0, 0);
  12189. }
  12190. }
  12191. if (this.rotationQuaternion) {
  12192. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12193. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12194. }
  12195. else {
  12196. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12197. this._cache.rotation.copyFrom(this.rotation);
  12198. }
  12199. // Translation
  12200. if (this.infiniteDistance && !this.parent) {
  12201. var camera = this.getScene().activeCamera;
  12202. if (camera) {
  12203. var cameraWorldMatrix = camera.getWorldMatrix();
  12204. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12205. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12206. }
  12207. }
  12208. else {
  12209. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12210. }
  12211. // Composing transformations
  12212. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12213. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12214. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12215. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12216. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12217. // Need to decompose each rotation here
  12218. var currentPosition = BABYLON.Tmp.Vector3[3];
  12219. if (this.parent && this.parent.getWorldMatrix) {
  12220. if (this._meshToBoneReferal) {
  12221. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12222. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12223. }
  12224. else {
  12225. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12226. }
  12227. }
  12228. else {
  12229. currentPosition.copyFrom(this.position);
  12230. }
  12231. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12232. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12233. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12234. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12235. }
  12236. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12237. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12238. }
  12239. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12240. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12241. }
  12242. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12243. }
  12244. else {
  12245. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12246. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12247. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12248. }
  12249. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12250. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12251. }
  12252. // Local world
  12253. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12254. // Parent
  12255. if (this.parent && this.parent.getWorldMatrix) {
  12256. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12257. if (this._meshToBoneReferal) {
  12258. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12259. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12260. }
  12261. else {
  12262. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12263. }
  12264. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12265. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12266. this._worldMatrix.copyFrom(this._localWorld);
  12267. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12268. }
  12269. else {
  12270. if (this._meshToBoneReferal) {
  12271. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12272. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12273. }
  12274. else {
  12275. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12276. }
  12277. }
  12278. this._markSyncedWithParent();
  12279. }
  12280. else {
  12281. this._worldMatrix.copyFrom(this._localWorld);
  12282. }
  12283. // Bounding info
  12284. this._updateBoundingInfo();
  12285. // Absolute position
  12286. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12287. // Callbacks
  12288. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12289. if (!this._poseMatrix) {
  12290. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12291. }
  12292. return this._worldMatrix;
  12293. };
  12294. /**
  12295. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12296. * @param func: callback function to add
  12297. *
  12298. * Returns the AbstractMesh.
  12299. */
  12300. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12301. this.onAfterWorldMatrixUpdateObservable.add(func);
  12302. return this;
  12303. };
  12304. /**
  12305. * Removes a registered callback function.
  12306. * Returns the AbstractMesh.
  12307. */
  12308. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12309. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12310. return this;
  12311. };
  12312. /**
  12313. * Sets the mesh position in its local space.
  12314. * Returns the AbstractMesh.
  12315. */
  12316. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12317. this.computeWorldMatrix();
  12318. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12319. return this;
  12320. };
  12321. /**
  12322. * Returns the mesh position in the local space from the current World matrix values.
  12323. * Returns a new Vector3.
  12324. */
  12325. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12326. this.computeWorldMatrix();
  12327. var invLocalWorldMatrix = this._localWorld.clone();
  12328. invLocalWorldMatrix.invert();
  12329. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12330. };
  12331. /**
  12332. * Translates the mesh along the passed Vector3 in its local space.
  12333. * Returns the AbstractMesh.
  12334. */
  12335. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12336. this.computeWorldMatrix(true);
  12337. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12338. return this;
  12339. };
  12340. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12341. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12342. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12343. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12344. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12345. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12346. /// <returns>Mesh oriented towards targetMesh</returns>
  12347. if (yawCor === void 0) { yawCor = 0; }
  12348. if (pitchCor === void 0) { pitchCor = 0; }
  12349. if (rollCor === void 0) { rollCor = 0; }
  12350. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12351. var dv = AbstractMesh._lookAtVectorCache;
  12352. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12353. targetPoint.subtractToRef(pos, dv);
  12354. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12355. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12356. var pitch = Math.atan2(dv.y, len);
  12357. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12358. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12359. return this;
  12360. };
  12361. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12362. this._meshToBoneReferal = affectedMesh;
  12363. this.parent = bone;
  12364. if (bone.getWorldMatrix().determinant() < 0) {
  12365. this.scalingDeterminant *= -1;
  12366. }
  12367. return this;
  12368. };
  12369. AbstractMesh.prototype.detachFromBone = function () {
  12370. if (this.parent.getWorldMatrix().determinant() < 0) {
  12371. this.scalingDeterminant *= -1;
  12372. }
  12373. this._meshToBoneReferal = null;
  12374. this.parent = null;
  12375. return this;
  12376. };
  12377. /**
  12378. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12379. * A mesh is in the frustum if its bounding box intersects the frustum.
  12380. * Boolean returned.
  12381. */
  12382. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12383. return this._boundingInfo.isInFrustum(frustumPlanes);
  12384. };
  12385. /**
  12386. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12387. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12388. * Boolean returned.
  12389. */
  12390. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12391. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12392. ;
  12393. };
  12394. /**
  12395. * True if the mesh intersects another mesh or a SolidParticle object.
  12396. * 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)
  12397. * Returns a boolean.
  12398. */
  12399. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12400. if (!this._boundingInfo || !mesh._boundingInfo) {
  12401. return false;
  12402. }
  12403. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12404. };
  12405. /**
  12406. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12407. * Returns a boolean.
  12408. */
  12409. AbstractMesh.prototype.intersectsPoint = function (point) {
  12410. if (!this._boundingInfo) {
  12411. return false;
  12412. }
  12413. return this._boundingInfo.intersectsPoint(point);
  12414. };
  12415. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12416. return this.physicsImpostor;
  12417. };
  12418. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12419. if (!camera) {
  12420. camera = this.getScene().activeCamera;
  12421. }
  12422. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12423. };
  12424. /**
  12425. * Returns the distance from the mesh to the active camera.
  12426. * Returns a float.
  12427. */
  12428. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12429. if (!camera) {
  12430. camera = this.getScene().activeCamera;
  12431. }
  12432. return this.absolutePosition.subtract(camera.position).length();
  12433. };
  12434. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12435. if (!this.physicsImpostor) {
  12436. return;
  12437. }
  12438. this.physicsImpostor.applyImpulse(force, contactPoint);
  12439. return this;
  12440. };
  12441. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12442. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12443. return;
  12444. }
  12445. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12446. mainPivot: pivot1,
  12447. connectedPivot: pivot2,
  12448. nativeParams: options
  12449. });
  12450. return this;
  12451. };
  12452. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12453. // Collisions
  12454. /**
  12455. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12456. * Default `false`.
  12457. */
  12458. get: function () {
  12459. return this._checkCollisions;
  12460. },
  12461. set: function (collisionEnabled) {
  12462. this._checkCollisions = collisionEnabled;
  12463. if (this.getScene().workerCollisions) {
  12464. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12465. }
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12471. var globalPosition = this.getAbsolutePosition();
  12472. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12473. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12474. if (!this._collider) {
  12475. this._collider = new BABYLON.Collider();
  12476. }
  12477. this._collider.radius = this.ellipsoid;
  12478. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12479. return this;
  12480. };
  12481. // Submeshes octree
  12482. /**
  12483. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12484. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12485. * Returns an Octree of submeshes.
  12486. */
  12487. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12488. if (maxCapacity === void 0) { maxCapacity = 64; }
  12489. if (maxDepth === void 0) { maxDepth = 2; }
  12490. if (!this._submeshesOctree) {
  12491. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12492. }
  12493. this.computeWorldMatrix(true);
  12494. // Update octree
  12495. var bbox = this.getBoundingInfo().boundingBox;
  12496. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12497. return this._submeshesOctree;
  12498. };
  12499. // Collisions
  12500. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12501. this._generatePointsArray();
  12502. // Transformation
  12503. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12504. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12505. subMesh._lastColliderWorldVertices = [];
  12506. subMesh._trianglePlanes = [];
  12507. var start = subMesh.verticesStart;
  12508. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12509. for (var i = start; i < end; i++) {
  12510. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12511. }
  12512. }
  12513. // Collide
  12514. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12515. if (collider.collisionFound) {
  12516. collider.collidedMesh = this;
  12517. }
  12518. return this;
  12519. };
  12520. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12521. var subMeshes;
  12522. var len;
  12523. // Octrees
  12524. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12525. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12526. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12527. len = intersections.length;
  12528. subMeshes = intersections.data;
  12529. }
  12530. else {
  12531. subMeshes = this.subMeshes;
  12532. len = subMeshes.length;
  12533. }
  12534. for (var index = 0; index < len; index++) {
  12535. var subMesh = subMeshes[index];
  12536. // Bounding test
  12537. if (len > 1 && !subMesh._checkCollision(collider))
  12538. continue;
  12539. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12540. }
  12541. return this;
  12542. };
  12543. AbstractMesh.prototype._checkCollision = function (collider) {
  12544. // Bounding box test
  12545. if (!this._boundingInfo._checkCollision(collider))
  12546. return this;
  12547. // Transformation matrix
  12548. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12549. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12550. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12551. return this;
  12552. };
  12553. // Picking
  12554. AbstractMesh.prototype._generatePointsArray = function () {
  12555. return false;
  12556. };
  12557. /**
  12558. * Checks if the passed Ray intersects with the mesh.
  12559. * Returns an object PickingInfo.
  12560. */
  12561. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12562. var pickingInfo = new BABYLON.PickingInfo();
  12563. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12564. return pickingInfo;
  12565. }
  12566. if (!this._generatePointsArray()) {
  12567. return pickingInfo;
  12568. }
  12569. var intersectInfo = null;
  12570. // Octrees
  12571. var subMeshes;
  12572. var len;
  12573. if (this._submeshesOctree && this.useOctreeForPicking) {
  12574. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12575. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12576. len = intersections.length;
  12577. subMeshes = intersections.data;
  12578. }
  12579. else {
  12580. subMeshes = this.subMeshes;
  12581. len = subMeshes.length;
  12582. }
  12583. for (var index = 0; index < len; index++) {
  12584. var subMesh = subMeshes[index];
  12585. // Bounding test
  12586. if (len > 1 && !subMesh.canIntersects(ray))
  12587. continue;
  12588. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12589. if (currentIntersectInfo) {
  12590. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12591. intersectInfo = currentIntersectInfo;
  12592. intersectInfo.subMeshId = index;
  12593. if (fastCheck) {
  12594. break;
  12595. }
  12596. }
  12597. }
  12598. }
  12599. if (intersectInfo) {
  12600. // Get picked point
  12601. var world = this.getWorldMatrix();
  12602. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12603. var direction = ray.direction.clone();
  12604. direction = direction.scale(intersectInfo.distance);
  12605. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12606. var pickedPoint = worldOrigin.add(worldDirection);
  12607. // Return result
  12608. pickingInfo.hit = true;
  12609. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12610. pickingInfo.pickedPoint = pickedPoint;
  12611. pickingInfo.pickedMesh = this;
  12612. pickingInfo.bu = intersectInfo.bu;
  12613. pickingInfo.bv = intersectInfo.bv;
  12614. pickingInfo.faceId = intersectInfo.faceId;
  12615. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12616. return pickingInfo;
  12617. }
  12618. return pickingInfo;
  12619. };
  12620. /**
  12621. * Clones the mesh, used by the class Mesh.
  12622. * Just returns `null` for an AbstractMesh.
  12623. */
  12624. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12625. return null;
  12626. };
  12627. /**
  12628. * Disposes all the mesh submeshes.
  12629. * Returns the AbstractMesh.
  12630. */
  12631. AbstractMesh.prototype.releaseSubMeshes = function () {
  12632. if (this.subMeshes) {
  12633. while (this.subMeshes.length) {
  12634. this.subMeshes[0].dispose();
  12635. }
  12636. }
  12637. else {
  12638. this.subMeshes = new Array();
  12639. }
  12640. return this;
  12641. };
  12642. /**
  12643. * Disposes the AbstractMesh.
  12644. * Some internal references are kept for further use.
  12645. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12646. * Returns nothing.
  12647. */
  12648. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12649. var _this = this;
  12650. var index;
  12651. // Action manager
  12652. if (this.actionManager) {
  12653. this.actionManager.dispose();
  12654. this.actionManager = null;
  12655. }
  12656. // Skeleton
  12657. this.skeleton = null;
  12658. // Animations
  12659. this.getScene().stopAnimation(this);
  12660. // Physics
  12661. if (this.physicsImpostor) {
  12662. this.physicsImpostor.dispose();
  12663. }
  12664. // Intersections in progress
  12665. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12666. var other = this._intersectionsInProgress[index];
  12667. var pos = other._intersectionsInProgress.indexOf(this);
  12668. other._intersectionsInProgress.splice(pos, 1);
  12669. }
  12670. this._intersectionsInProgress = [];
  12671. // Lights
  12672. var lights = this.getScene().lights;
  12673. lights.forEach(function (light) {
  12674. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12675. if (meshIndex !== -1) {
  12676. light.includedOnlyMeshes.splice(meshIndex, 1);
  12677. }
  12678. meshIndex = light.excludedMeshes.indexOf(_this);
  12679. if (meshIndex !== -1) {
  12680. light.excludedMeshes.splice(meshIndex, 1);
  12681. }
  12682. // Shadow generators
  12683. var generator = light.getShadowGenerator();
  12684. if (generator) {
  12685. var shadowMap = generator.getShadowMap();
  12686. meshIndex = shadowMap.renderList.indexOf(_this);
  12687. if (meshIndex !== -1) {
  12688. shadowMap.renderList.splice(meshIndex, 1);
  12689. }
  12690. }
  12691. });
  12692. // Edges
  12693. if (this._edgesRenderer) {
  12694. this._edgesRenderer.dispose();
  12695. this._edgesRenderer = null;
  12696. }
  12697. // SubMeshes
  12698. if (this.getClassName() !== "InstancedMesh") {
  12699. this.releaseSubMeshes();
  12700. }
  12701. // Octree
  12702. var sceneOctree = this.getScene().selectionOctree;
  12703. if (sceneOctree) {
  12704. var index = sceneOctree.dynamicContent.indexOf(this);
  12705. if (index !== -1) {
  12706. sceneOctree.dynamicContent.splice(index, 1);
  12707. }
  12708. }
  12709. // Engine
  12710. this.getScene().getEngine().wipeCaches();
  12711. // Remove from scene
  12712. this.getScene().removeMesh(this);
  12713. if (!doNotRecurse) {
  12714. // Particles
  12715. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12716. if (this.getScene().particleSystems[index].emitter === this) {
  12717. this.getScene().particleSystems[index].dispose();
  12718. index--;
  12719. }
  12720. }
  12721. // Children
  12722. var objects = this.getDescendants(true);
  12723. for (index = 0; index < objects.length; index++) {
  12724. objects[index].dispose();
  12725. }
  12726. }
  12727. else {
  12728. var childMeshes = this.getChildMeshes(true);
  12729. for (index = 0; index < childMeshes.length; index++) {
  12730. var child = childMeshes[index];
  12731. child.parent = null;
  12732. child.computeWorldMatrix(true);
  12733. }
  12734. }
  12735. // facet data
  12736. if (this._facetDataEnabled) {
  12737. this.disableFacetData();
  12738. }
  12739. this.onAfterWorldMatrixUpdateObservable.clear();
  12740. this.onCollideObservable.clear();
  12741. this.onCollisionPositionChangeObservable.clear();
  12742. this._isDisposed = true;
  12743. _super.prototype.dispose.call(this);
  12744. };
  12745. /**
  12746. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12747. * This Vector3 is expressed in the World space.
  12748. */
  12749. AbstractMesh.prototype.getDirection = function (localAxis) {
  12750. var result = BABYLON.Vector3.Zero();
  12751. this.getDirectionToRef(localAxis, result);
  12752. return result;
  12753. };
  12754. /**
  12755. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12756. * localAxis is expressed in the mesh local space.
  12757. * result is computed in the Wordl space from the mesh World matrix.
  12758. * Returns the AbstractMesh.
  12759. */
  12760. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12761. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12762. return this;
  12763. };
  12764. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12765. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12766. if (this.getScene().getRenderId() == 0) {
  12767. this.computeWorldMatrix(true);
  12768. }
  12769. var wm = this.getWorldMatrix();
  12770. if (space == BABYLON.Space.WORLD) {
  12771. var tmat = BABYLON.Tmp.Matrix[0];
  12772. wm.invertToRef(tmat);
  12773. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12774. }
  12775. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12776. this._pivotMatrix.m[12] = -point.x;
  12777. this._pivotMatrix.m[13] = -point.y;
  12778. this._pivotMatrix.m[14] = -point.z;
  12779. this._cache.pivotMatrixUpdated = true;
  12780. return this;
  12781. };
  12782. /**
  12783. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12784. */
  12785. AbstractMesh.prototype.getPivotPoint = function () {
  12786. var point = BABYLON.Vector3.Zero();
  12787. this.getPivotPointToRef(point);
  12788. return point;
  12789. };
  12790. /**
  12791. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12792. * Returns the AbstractMesh.
  12793. */
  12794. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12795. result.x = -this._pivotMatrix.m[12];
  12796. result.y = -this._pivotMatrix.m[13];
  12797. result.z = -this._pivotMatrix.m[14];
  12798. return this;
  12799. };
  12800. /**
  12801. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12802. */
  12803. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12804. var point = BABYLON.Vector3.Zero();
  12805. this.getAbsolutePivotPointToRef(point);
  12806. return point;
  12807. };
  12808. /**
  12809. * Defines the passed mesh as the parent of the current mesh.
  12810. * Returns the AbstractMesh.
  12811. */
  12812. AbstractMesh.prototype.setParent = function (mesh) {
  12813. var child = this;
  12814. var parent = mesh;
  12815. if (mesh == null) {
  12816. var rotation = BABYLON.Tmp.Quaternion[0];
  12817. var position = BABYLON.Tmp.Vector3[0];
  12818. var scale = BABYLON.Tmp.Vector3[1];
  12819. child.getWorldMatrix().decompose(scale, rotation, position);
  12820. if (child.rotationQuaternion) {
  12821. child.rotationQuaternion.copyFrom(rotation);
  12822. }
  12823. else {
  12824. rotation.toEulerAnglesToRef(child.rotation);
  12825. }
  12826. child.position.x = position.x;
  12827. child.position.y = position.y;
  12828. child.position.z = position.z;
  12829. }
  12830. else {
  12831. var rotation = BABYLON.Tmp.Quaternion[0];
  12832. var position = BABYLON.Tmp.Vector3[0];
  12833. var scale = BABYLON.Tmp.Vector3[1];
  12834. var m1 = BABYLON.Tmp.Matrix[0];
  12835. var m2 = BABYLON.Tmp.Matrix[1];
  12836. parent.getWorldMatrix().decompose(scale, rotation, position);
  12837. rotation.toRotationMatrix(m1);
  12838. m2.setTranslation(position);
  12839. m2.multiplyToRef(m1, m1);
  12840. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12841. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12842. m.decompose(scale, rotation, position);
  12843. if (child.rotationQuaternion) {
  12844. child.rotationQuaternion.copyFrom(rotation);
  12845. }
  12846. else {
  12847. rotation.toEulerAnglesToRef(child.rotation);
  12848. }
  12849. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12850. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12851. m.decompose(scale, rotation, position);
  12852. child.position.x = position.x;
  12853. child.position.y = position.y;
  12854. child.position.z = position.z;
  12855. }
  12856. child.parent = parent;
  12857. return this;
  12858. };
  12859. /**
  12860. * Adds the passed mesh as a child to the current mesh.
  12861. * Returns the AbstractMesh.
  12862. */
  12863. AbstractMesh.prototype.addChild = function (mesh) {
  12864. mesh.setParent(this);
  12865. return this;
  12866. };
  12867. /**
  12868. * Removes the passed mesh from the current mesh children list.
  12869. * Returns the AbstractMesh.
  12870. */
  12871. AbstractMesh.prototype.removeChild = function (mesh) {
  12872. mesh.setParent(null);
  12873. return this;
  12874. };
  12875. /**
  12876. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12877. * Returns the AbstractMesh.
  12878. */
  12879. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12880. result.x = this._pivotMatrix.m[12];
  12881. result.y = this._pivotMatrix.m[13];
  12882. result.z = this._pivotMatrix.m[14];
  12883. this.getPivotPointToRef(result);
  12884. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12885. return this;
  12886. };
  12887. // Facet data
  12888. /**
  12889. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12890. * Returns the AbstractMesh.
  12891. */
  12892. AbstractMesh.prototype._initFacetData = function () {
  12893. if (!this._facetNormals) {
  12894. this._facetNormals = new Array();
  12895. }
  12896. if (!this._facetPositions) {
  12897. this._facetPositions = new Array();
  12898. }
  12899. if (!this._facetPartitioning) {
  12900. this._facetPartitioning = new Array();
  12901. }
  12902. this._facetNb = this.getIndices().length / 3;
  12903. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12904. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12905. for (var f = 0; f < this._facetNb; f++) {
  12906. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12907. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12908. }
  12909. this._facetDataEnabled = true;
  12910. return this;
  12911. };
  12912. /**
  12913. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12914. * This method can be called within the render loop.
  12915. * 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.
  12916. * Returns the AbstractMesh.
  12917. */
  12918. AbstractMesh.prototype.updateFacetData = function () {
  12919. if (!this._facetDataEnabled) {
  12920. this._initFacetData();
  12921. }
  12922. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12923. var indices = this.getIndices();
  12924. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12925. var bInfo = this.getBoundingInfo();
  12926. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12927. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12928. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12929. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12930. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12931. this._subDiv.max = this._partitioningSubdivisions;
  12932. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12933. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12934. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12935. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12936. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12937. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12938. // set the parameters for ComputeNormals()
  12939. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12940. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12941. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12942. this._facetParameters.bInfo = bInfo;
  12943. this._facetParameters.bbSize = this._bbSize;
  12944. this._facetParameters.subDiv = this._subDiv;
  12945. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12946. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12947. return this;
  12948. };
  12949. /**
  12950. * Returns the facetLocalNormals array.
  12951. * The normals are expressed in the mesh local space.
  12952. */
  12953. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12954. if (!this._facetNormals) {
  12955. this.updateFacetData();
  12956. }
  12957. return this._facetNormals;
  12958. };
  12959. /**
  12960. * Returns the facetLocalPositions array.
  12961. * The facet positions are expressed in the mesh local space.
  12962. */
  12963. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12964. if (!this._facetPositions) {
  12965. this.updateFacetData();
  12966. }
  12967. return this._facetPositions;
  12968. };
  12969. /**
  12970. * Returns the facetLocalPartioning array.
  12971. */
  12972. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12973. if (!this._facetPartitioning) {
  12974. this.updateFacetData();
  12975. }
  12976. return this._facetPartitioning;
  12977. };
  12978. /**
  12979. * Returns the i-th facet position in the world system.
  12980. * This method allocates a new Vector3 per call.
  12981. */
  12982. AbstractMesh.prototype.getFacetPosition = function (i) {
  12983. var pos = BABYLON.Vector3.Zero();
  12984. this.getFacetPositionToRef(i, pos);
  12985. return pos;
  12986. };
  12987. /**
  12988. * Sets the reference Vector3 with the i-th facet position in the world system.
  12989. * Returns the AbstractMesh.
  12990. */
  12991. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12992. var localPos = (this.getFacetLocalPositions())[i];
  12993. var world = this.getWorldMatrix();
  12994. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12995. return this;
  12996. };
  12997. /**
  12998. * Returns the i-th facet normal in the world system.
  12999. * This method allocates a new Vector3 per call.
  13000. */
  13001. AbstractMesh.prototype.getFacetNormal = function (i) {
  13002. var norm = BABYLON.Vector3.Zero();
  13003. this.getFacetNormalToRef(i, norm);
  13004. return norm;
  13005. };
  13006. /**
  13007. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13008. * Returns the AbstractMesh.
  13009. */
  13010. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13011. var localNorm = (this.getFacetLocalNormals())[i];
  13012. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13013. return this;
  13014. };
  13015. /**
  13016. * 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).
  13017. */
  13018. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13019. var bInfo = this.getBoundingInfo();
  13020. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13021. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13022. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13023. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13024. return null;
  13025. }
  13026. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13027. };
  13028. /**
  13029. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13030. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13031. * 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.
  13032. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13033. * 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.
  13034. */
  13035. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13036. if (checkFace === void 0) { checkFace = false; }
  13037. if (facing === void 0) { facing = true; }
  13038. var world = this.getWorldMatrix();
  13039. var invMat = BABYLON.Tmp.Matrix[5];
  13040. world.invertToRef(invMat);
  13041. var invVect = BABYLON.Tmp.Vector3[8];
  13042. var closest = null;
  13043. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13044. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13045. if (projected) {
  13046. // tranform the local computed projected vector to world coordinates
  13047. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13048. }
  13049. return closest;
  13050. };
  13051. /**
  13052. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13053. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13054. * 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.
  13055. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13056. * 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.
  13057. */
  13058. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13059. if (checkFace === void 0) { checkFace = false; }
  13060. if (facing === void 0) { facing = true; }
  13061. var closest = null;
  13062. var tmpx = 0.0;
  13063. var tmpy = 0.0;
  13064. var tmpz = 0.0;
  13065. var d = 0.0; // tmp dot facet normal * facet position
  13066. var t0 = 0.0;
  13067. var projx = 0.0;
  13068. var projy = 0.0;
  13069. var projz = 0.0;
  13070. // Get all the facets in the same partitioning block than (x, y, z)
  13071. var facetPositions = this.getFacetLocalPositions();
  13072. var facetNormals = this.getFacetLocalNormals();
  13073. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13074. if (!facetsInBlock) {
  13075. return null;
  13076. }
  13077. // Get the closest facet to (x, y, z)
  13078. var shortest = Number.MAX_VALUE; // init distance vars
  13079. var tmpDistance = shortest;
  13080. var fib; // current facet in the block
  13081. var norm; // current facet normal
  13082. var p0; // current facet barycenter position
  13083. // loop on all the facets in the current partitioning block
  13084. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13085. fib = facetsInBlock[idx];
  13086. norm = facetNormals[fib];
  13087. p0 = facetPositions[fib];
  13088. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13089. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13090. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13091. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13092. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13093. projx = x + norm.x * t0;
  13094. projy = y + norm.y * t0;
  13095. projz = z + norm.z * t0;
  13096. tmpx = projx - x;
  13097. tmpy = projy - y;
  13098. tmpz = projz - z;
  13099. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13100. if (tmpDistance < shortest) {
  13101. shortest = tmpDistance;
  13102. closest = fib;
  13103. if (projected) {
  13104. projected.x = projx;
  13105. projected.y = projy;
  13106. projected.z = projz;
  13107. }
  13108. }
  13109. }
  13110. }
  13111. return closest;
  13112. };
  13113. /**
  13114. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13115. */
  13116. AbstractMesh.prototype.getFacetDataParameters = function () {
  13117. return this._facetParameters;
  13118. };
  13119. /**
  13120. * Disables the feature FacetData and frees the related memory.
  13121. * Returns the AbstractMesh.
  13122. */
  13123. AbstractMesh.prototype.disableFacetData = function () {
  13124. if (this._facetDataEnabled) {
  13125. this._facetDataEnabled = false;
  13126. this._facetPositions = null;
  13127. this._facetNormals = null;
  13128. this._facetPartitioning = null;
  13129. this._facetParameters = null;
  13130. }
  13131. return this;
  13132. };
  13133. /**
  13134. * Creates new normals data for the mesh.
  13135. * @param updatable.
  13136. */
  13137. AbstractMesh.prototype.createNormals = function (updatable) {
  13138. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13139. var indices = this.getIndices();
  13140. var normals;
  13141. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13142. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13143. }
  13144. else {
  13145. normals = [];
  13146. }
  13147. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13148. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13149. };
  13150. return AbstractMesh;
  13151. }(BABYLON.Node));
  13152. // Statics
  13153. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13154. AbstractMesh._BILLBOARDMODE_X = 1;
  13155. AbstractMesh._BILLBOARDMODE_Y = 2;
  13156. AbstractMesh._BILLBOARDMODE_Z = 4;
  13157. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13158. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13159. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13160. BABYLON.AbstractMesh = AbstractMesh;
  13161. })(BABYLON || (BABYLON = {}));
  13162. //# sourceMappingURL=babylon.abstractMesh.js.map
  13163. var BABYLON;
  13164. (function (BABYLON) {
  13165. var Light = (function (_super) {
  13166. __extends(Light, _super);
  13167. /**
  13168. * Creates a Light object in the scene.
  13169. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13170. */
  13171. function Light(name, scene) {
  13172. var _this = _super.call(this, name, scene) || this;
  13173. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13174. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13175. _this.intensity = 1.0;
  13176. _this.range = Number.MAX_VALUE;
  13177. /**
  13178. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13179. * of light.
  13180. */
  13181. _this._photometricScale = 1.0;
  13182. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13183. _this._radius = 0.00001;
  13184. _this.renderPriority = 0;
  13185. /**
  13186. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13187. * the current shadow generator.
  13188. */
  13189. _this.shadowEnabled = true;
  13190. _this._excludeWithLayerMask = 0;
  13191. _this._includeOnlyWithLayerMask = 0;
  13192. _this._lightmapMode = 0;
  13193. _this._excludedMeshesIds = new Array();
  13194. _this._includedOnlyMeshesIds = new Array();
  13195. _this.getScene().addLight(_this);
  13196. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13197. _this._buildUniformLayout();
  13198. _this.includedOnlyMeshes = new Array();
  13199. _this.excludedMeshes = new Array();
  13200. _this._resyncMeshes();
  13201. return _this;
  13202. }
  13203. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13204. /**
  13205. * If every light affecting the material is in this lightmapMode,
  13206. * material.lightmapTexture adds or multiplies
  13207. * (depends on material.useLightmapAsShadowmap)
  13208. * after every other light calculations.
  13209. */
  13210. get: function () {
  13211. return Light._LIGHTMAP_DEFAULT;
  13212. },
  13213. enumerable: true,
  13214. configurable: true
  13215. });
  13216. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13217. /**
  13218. * material.lightmapTexture as only diffuse lighting from this light
  13219. * adds pnly specular lighting from this light
  13220. * adds dynamic shadows
  13221. */
  13222. get: function () {
  13223. return Light._LIGHTMAP_SPECULAR;
  13224. },
  13225. enumerable: true,
  13226. configurable: true
  13227. });
  13228. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13229. /**
  13230. * material.lightmapTexture as only lighting
  13231. * no light calculation from this light
  13232. * only adds dynamic shadows from this light
  13233. */
  13234. get: function () {
  13235. return Light._LIGHTMAP_SHADOWSONLY;
  13236. },
  13237. enumerable: true,
  13238. configurable: true
  13239. });
  13240. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13241. /**
  13242. * Each light type uses the default quantity according to its type:
  13243. * point/spot lights use luminous intensity
  13244. * directional lights use illuminance
  13245. */
  13246. get: function () {
  13247. return Light._INTENSITYMODE_AUTOMATIC;
  13248. },
  13249. enumerable: true,
  13250. configurable: true
  13251. });
  13252. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13253. /**
  13254. * lumen (lm)
  13255. */
  13256. get: function () {
  13257. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13258. },
  13259. enumerable: true,
  13260. configurable: true
  13261. });
  13262. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13263. /**
  13264. * candela (lm/sr)
  13265. */
  13266. get: function () {
  13267. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13268. },
  13269. enumerable: true,
  13270. configurable: true
  13271. });
  13272. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13273. /**
  13274. * lux (lm/m^2)
  13275. */
  13276. get: function () {
  13277. return Light._INTENSITYMODE_ILLUMINANCE;
  13278. },
  13279. enumerable: true,
  13280. configurable: true
  13281. });
  13282. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13283. /**
  13284. * nit (cd/m^2)
  13285. */
  13286. get: function () {
  13287. return Light._INTENSITYMODE_LUMINANCE;
  13288. },
  13289. enumerable: true,
  13290. configurable: true
  13291. });
  13292. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13293. /**
  13294. * Light type const id of the point light.
  13295. */
  13296. get: function () {
  13297. return Light._LIGHTTYPEID_POINTLIGHT;
  13298. },
  13299. enumerable: true,
  13300. configurable: true
  13301. });
  13302. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13303. /**
  13304. * Light type const id of the directional light.
  13305. */
  13306. get: function () {
  13307. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13308. },
  13309. enumerable: true,
  13310. configurable: true
  13311. });
  13312. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13313. /**
  13314. * Light type const id of the spot light.
  13315. */
  13316. get: function () {
  13317. return Light._LIGHTTYPEID_SPOTLIGHT;
  13318. },
  13319. enumerable: true,
  13320. configurable: true
  13321. });
  13322. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13323. /**
  13324. * Light type const id of the hemispheric light.
  13325. */
  13326. get: function () {
  13327. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13328. },
  13329. enumerable: true,
  13330. configurable: true
  13331. });
  13332. Object.defineProperty(Light.prototype, "intensityMode", {
  13333. /**
  13334. * Gets the photometric scale used to interpret the intensity.
  13335. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13336. */
  13337. get: function () {
  13338. return this._intensityMode;
  13339. },
  13340. /**
  13341. * Sets the photometric scale used to interpret the intensity.
  13342. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13343. */
  13344. set: function (value) {
  13345. this._intensityMode = value;
  13346. this._computePhotometricScale();
  13347. },
  13348. enumerable: true,
  13349. configurable: true
  13350. });
  13351. ;
  13352. ;
  13353. Object.defineProperty(Light.prototype, "radius", {
  13354. /**
  13355. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13356. */
  13357. get: function () {
  13358. return this._radius;
  13359. },
  13360. /**
  13361. * sets the light radius used by PBR Materials to simulate soft area lights.
  13362. */
  13363. set: function (value) {
  13364. this._radius = value;
  13365. this._computePhotometricScale();
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. ;
  13371. ;
  13372. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13373. get: function () {
  13374. return this._includedOnlyMeshes;
  13375. },
  13376. set: function (value) {
  13377. this._includedOnlyMeshes = value;
  13378. this._hookArrayForIncludedOnly(value);
  13379. },
  13380. enumerable: true,
  13381. configurable: true
  13382. });
  13383. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13384. get: function () {
  13385. return this._excludedMeshes;
  13386. },
  13387. set: function (value) {
  13388. this._excludedMeshes = value;
  13389. this._hookArrayForExcluded(value);
  13390. },
  13391. enumerable: true,
  13392. configurable: true
  13393. });
  13394. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13395. get: function () {
  13396. return this._excludeWithLayerMask;
  13397. },
  13398. set: function (value) {
  13399. this._excludeWithLayerMask = value;
  13400. this._resyncMeshes();
  13401. },
  13402. enumerable: true,
  13403. configurable: true
  13404. });
  13405. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13406. get: function () {
  13407. return this._includeOnlyWithLayerMask;
  13408. },
  13409. set: function (value) {
  13410. this._includeOnlyWithLayerMask = value;
  13411. this._resyncMeshes();
  13412. },
  13413. enumerable: true,
  13414. configurable: true
  13415. });
  13416. Object.defineProperty(Light.prototype, "lightmapMode", {
  13417. get: function () {
  13418. return this._lightmapMode;
  13419. },
  13420. set: function (value) {
  13421. if (this._lightmapMode === value) {
  13422. return;
  13423. }
  13424. this._lightmapMode = value;
  13425. this._markMeshesAsLightDirty();
  13426. },
  13427. enumerable: true,
  13428. configurable: true
  13429. });
  13430. Light.prototype._buildUniformLayout = function () {
  13431. // Overridden
  13432. };
  13433. /**
  13434. * Returns the string "Light".
  13435. */
  13436. Light.prototype.getClassName = function () {
  13437. return "Light";
  13438. };
  13439. /**
  13440. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13441. */
  13442. Light.prototype.toString = function (fullDetails) {
  13443. var ret = "Name: " + this.name;
  13444. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13445. if (this.animations) {
  13446. for (var i = 0; i < this.animations.length; i++) {
  13447. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13448. }
  13449. }
  13450. if (fullDetails) {
  13451. }
  13452. return ret;
  13453. };
  13454. /**
  13455. * Set the enabled state of this node.
  13456. * @param {boolean} value - the new enabled state
  13457. * @see isEnabled
  13458. */
  13459. Light.prototype.setEnabled = function (value) {
  13460. _super.prototype.setEnabled.call(this, value);
  13461. this._resyncMeshes();
  13462. };
  13463. /**
  13464. * Returns the Light associated shadow generator.
  13465. */
  13466. Light.prototype.getShadowGenerator = function () {
  13467. return this._shadowGenerator;
  13468. };
  13469. /**
  13470. * Returns a Vector3, the absolute light position in the World.
  13471. */
  13472. Light.prototype.getAbsolutePosition = function () {
  13473. return BABYLON.Vector3.Zero();
  13474. };
  13475. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13476. };
  13477. Light.prototype._getWorldMatrix = function () {
  13478. return BABYLON.Matrix.Identity();
  13479. };
  13480. /**
  13481. * Boolean : True if the light will affect the passed mesh.
  13482. */
  13483. Light.prototype.canAffectMesh = function (mesh) {
  13484. if (!mesh) {
  13485. return true;
  13486. }
  13487. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13488. return false;
  13489. }
  13490. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13491. return false;
  13492. }
  13493. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13494. return false;
  13495. }
  13496. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13497. return false;
  13498. }
  13499. return true;
  13500. };
  13501. /**
  13502. * Returns the light World matrix.
  13503. */
  13504. Light.prototype.getWorldMatrix = function () {
  13505. this._currentRenderId = this.getScene().getRenderId();
  13506. var worldMatrix = this._getWorldMatrix();
  13507. if (this.parent && this.parent.getWorldMatrix) {
  13508. if (!this._parentedWorldMatrix) {
  13509. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13510. }
  13511. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13512. this._markSyncedWithParent();
  13513. return this._parentedWorldMatrix;
  13514. }
  13515. return worldMatrix;
  13516. };
  13517. /**
  13518. * Sort function to order lights for rendering.
  13519. * @param a First Light object to compare to second.
  13520. * @param b Second Light object to compare first.
  13521. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13522. */
  13523. Light.compareLightsPriority = function (a, b) {
  13524. //shadow-casting lights have priority over non-shadow-casting lights
  13525. //the renderPrioirty is a secondary sort criterion
  13526. if (a.shadowEnabled !== b.shadowEnabled) {
  13527. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13528. }
  13529. return b.renderPriority - a.renderPriority;
  13530. };
  13531. /**
  13532. * Disposes the light.
  13533. */
  13534. Light.prototype.dispose = function () {
  13535. if (this._shadowGenerator) {
  13536. this._shadowGenerator.dispose();
  13537. this._shadowGenerator = null;
  13538. }
  13539. // Animations
  13540. this.getScene().stopAnimation(this);
  13541. // Remove from meshes
  13542. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13543. var mesh = _a[_i];
  13544. mesh._removeLightSource(this);
  13545. }
  13546. this._uniformBuffer.dispose();
  13547. // Remove from scene
  13548. this.getScene().removeLight(this);
  13549. _super.prototype.dispose.call(this);
  13550. };
  13551. /**
  13552. * Returns the light type ID (integer).
  13553. */
  13554. Light.prototype.getTypeID = function () {
  13555. return 0;
  13556. };
  13557. /**
  13558. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13559. */
  13560. Light.prototype.getScaledIntensity = function () {
  13561. return this._photometricScale * this.intensity;
  13562. };
  13563. /**
  13564. * Returns a new Light object, named "name", from the current one.
  13565. */
  13566. Light.prototype.clone = function (name) {
  13567. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13568. };
  13569. /**
  13570. * Serializes the current light into a Serialization object.
  13571. * Returns the serialized object.
  13572. */
  13573. Light.prototype.serialize = function () {
  13574. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13575. // Type
  13576. serializationObject.type = this.getTypeID();
  13577. // Parent
  13578. if (this.parent) {
  13579. serializationObject.parentId = this.parent.id;
  13580. }
  13581. // Inclusion / exclusions
  13582. if (this.excludedMeshes.length > 0) {
  13583. serializationObject.excludedMeshesIds = [];
  13584. this.excludedMeshes.forEach(function (mesh) {
  13585. serializationObject.excludedMeshesIds.push(mesh.id);
  13586. });
  13587. }
  13588. if (this.includedOnlyMeshes.length > 0) {
  13589. serializationObject.includedOnlyMeshesIds = [];
  13590. this.includedOnlyMeshes.forEach(function (mesh) {
  13591. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13592. });
  13593. }
  13594. // Animations
  13595. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13596. serializationObject.ranges = this.serializeAnimationRanges();
  13597. return serializationObject;
  13598. };
  13599. /**
  13600. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13601. * This new light is named "name" and added to the passed scene.
  13602. */
  13603. Light.GetConstructorFromName = function (type, name, scene) {
  13604. switch (type) {
  13605. case 0:
  13606. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13607. case 1:
  13608. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13609. case 2:
  13610. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13611. case 3:
  13612. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13613. }
  13614. };
  13615. /**
  13616. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13617. */
  13618. Light.Parse = function (parsedLight, scene) {
  13619. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13620. // Inclusion / exclusions
  13621. if (parsedLight.excludedMeshesIds) {
  13622. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13623. }
  13624. if (parsedLight.includedOnlyMeshesIds) {
  13625. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13626. }
  13627. // Parent
  13628. if (parsedLight.parentId) {
  13629. light._waitingParentId = parsedLight.parentId;
  13630. }
  13631. // Animations
  13632. if (parsedLight.animations) {
  13633. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13634. var parsedAnimation = parsedLight.animations[animationIndex];
  13635. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13636. }
  13637. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13638. }
  13639. if (parsedLight.autoAnimate) {
  13640. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13641. }
  13642. return light;
  13643. };
  13644. Light.prototype._hookArrayForExcluded = function (array) {
  13645. var _this = this;
  13646. var oldPush = array.push;
  13647. array.push = function () {
  13648. var items = [];
  13649. for (var _i = 0; _i < arguments.length; _i++) {
  13650. items[_i] = arguments[_i];
  13651. }
  13652. var result = oldPush.apply(array, items);
  13653. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13654. var item = items_1[_a];
  13655. item._resyncLighSource(_this);
  13656. }
  13657. return result;
  13658. };
  13659. var oldSplice = array.splice;
  13660. array.splice = function (index, deleteCount) {
  13661. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13662. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13663. var item = deleted_1[_i];
  13664. item._resyncLighSource(_this);
  13665. }
  13666. return deleted;
  13667. };
  13668. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13669. var item = array_1[_i];
  13670. item._resyncLighSource(this);
  13671. }
  13672. };
  13673. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13674. var _this = this;
  13675. var oldPush = array.push;
  13676. array.push = function () {
  13677. var items = [];
  13678. for (var _i = 0; _i < arguments.length; _i++) {
  13679. items[_i] = arguments[_i];
  13680. }
  13681. var result = oldPush.apply(array, items);
  13682. _this._resyncMeshes();
  13683. return result;
  13684. };
  13685. var oldSplice = array.splice;
  13686. array.splice = function (index, deleteCount) {
  13687. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13688. _this._resyncMeshes();
  13689. return deleted;
  13690. };
  13691. this._resyncMeshes();
  13692. };
  13693. Light.prototype._resyncMeshes = function () {
  13694. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13695. var mesh = _a[_i];
  13696. mesh._resyncLighSource(this);
  13697. }
  13698. };
  13699. Light.prototype._markMeshesAsLightDirty = function () {
  13700. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13701. var mesh = _a[_i];
  13702. if (mesh._lightSources.indexOf(this) !== -1) {
  13703. mesh._markSubMeshesAsLightDirty();
  13704. }
  13705. }
  13706. };
  13707. /**
  13708. * Recomputes the cached photometric scale if needed.
  13709. */
  13710. Light.prototype._computePhotometricScale = function () {
  13711. this._photometricScale = this._getPhotometricScale();
  13712. this.getScene().resetCachedMaterial();
  13713. };
  13714. /**
  13715. * Returns the Photometric Scale according to the light type and intensity mode.
  13716. */
  13717. Light.prototype._getPhotometricScale = function () {
  13718. var photometricScale = 0.0;
  13719. var lightTypeID = this.getTypeID();
  13720. //get photometric mode
  13721. var photometricMode = this.intensityMode;
  13722. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13723. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13724. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13725. }
  13726. else {
  13727. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13728. }
  13729. }
  13730. //compute photometric scale
  13731. switch (lightTypeID) {
  13732. case Light.LIGHTTYPEID_POINTLIGHT:
  13733. case Light.LIGHTTYPEID_SPOTLIGHT:
  13734. switch (photometricMode) {
  13735. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13736. photometricScale = 1.0 / (4.0 * Math.PI);
  13737. break;
  13738. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13739. photometricScale = 1.0;
  13740. break;
  13741. case Light.INTENSITYMODE_LUMINANCE:
  13742. photometricScale = this.radius * this.radius;
  13743. break;
  13744. }
  13745. break;
  13746. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13747. switch (photometricMode) {
  13748. case Light.INTENSITYMODE_ILLUMINANCE:
  13749. photometricScale = 1.0;
  13750. break;
  13751. case Light.INTENSITYMODE_LUMINANCE:
  13752. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13753. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13754. var apexAngleRadians = this.radius;
  13755. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13756. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13757. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13758. photometricScale = solidAngle;
  13759. break;
  13760. }
  13761. break;
  13762. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13763. // No fall off in hemisperic light.
  13764. photometricScale = 1.0;
  13765. break;
  13766. }
  13767. return photometricScale;
  13768. };
  13769. Light.prototype._reorderLightsInScene = function () {
  13770. var scene = this.getScene();
  13771. if (this.renderPriority != 0) {
  13772. scene.requireLightSorting = true;
  13773. }
  13774. this.getScene().sortLightsByPriority();
  13775. };
  13776. return Light;
  13777. }(BABYLON.Node));
  13778. //lightmapMode Consts
  13779. Light._LIGHTMAP_DEFAULT = 0;
  13780. Light._LIGHTMAP_SPECULAR = 1;
  13781. Light._LIGHTMAP_SHADOWSONLY = 2;
  13782. // Intensity Mode Consts
  13783. Light._INTENSITYMODE_AUTOMATIC = 0;
  13784. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13785. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13786. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13787. Light._INTENSITYMODE_LUMINANCE = 4;
  13788. // Light types ids const.
  13789. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13790. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13791. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13792. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13793. __decorate([
  13794. BABYLON.serializeAsColor3()
  13795. ], Light.prototype, "diffuse", void 0);
  13796. __decorate([
  13797. BABYLON.serializeAsColor3()
  13798. ], Light.prototype, "specular", void 0);
  13799. __decorate([
  13800. BABYLON.serialize()
  13801. ], Light.prototype, "intensity", void 0);
  13802. __decorate([
  13803. BABYLON.serialize()
  13804. ], Light.prototype, "range", void 0);
  13805. __decorate([
  13806. BABYLON.serialize()
  13807. ], Light.prototype, "intensityMode", null);
  13808. __decorate([
  13809. BABYLON.serialize()
  13810. ], Light.prototype, "radius", null);
  13811. __decorate([
  13812. BABYLON.serialize()
  13813. ], Light.prototype, "_renderPriority", void 0);
  13814. __decorate([
  13815. BABYLON.expandToProperty("_reorderLightsInScene")
  13816. ], Light.prototype, "renderPriority", void 0);
  13817. __decorate([
  13818. BABYLON.serialize()
  13819. ], Light.prototype, "shadowEnabled", void 0);
  13820. __decorate([
  13821. BABYLON.serialize("excludeWithLayerMask")
  13822. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13823. __decorate([
  13824. BABYLON.serialize("includeOnlyWithLayerMask")
  13825. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13826. __decorate([
  13827. BABYLON.serialize("lightmapMode")
  13828. ], Light.prototype, "_lightmapMode", void 0);
  13829. BABYLON.Light = Light;
  13830. })(BABYLON || (BABYLON = {}));
  13831. //# sourceMappingURL=babylon.light.js.map
  13832. var BABYLON;
  13833. (function (BABYLON) {
  13834. var Camera = (function (_super) {
  13835. __extends(Camera, _super);
  13836. function Camera(name, position, scene) {
  13837. var _this = _super.call(this, name, scene) || this;
  13838. _this.upVector = BABYLON.Vector3.Up();
  13839. _this.orthoLeft = null;
  13840. _this.orthoRight = null;
  13841. _this.orthoBottom = null;
  13842. _this.orthoTop = null;
  13843. _this.fov = 0.8;
  13844. _this.minZ = 1.0;
  13845. _this.maxZ = 10000.0;
  13846. _this.inertia = 0.9;
  13847. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13848. _this.isIntermediate = false;
  13849. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13850. _this.layerMask = 0x0FFFFFFF;
  13851. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13852. // Camera rig members
  13853. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13854. _this._rigCameras = new Array();
  13855. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13856. // Cache
  13857. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13858. _this._projectionMatrix = new BABYLON.Matrix();
  13859. _this._doNotComputeProjectionMatrix = false;
  13860. _this._postProcesses = new Array();
  13861. _this._transformMatrix = BABYLON.Matrix.Zero();
  13862. _this._activeMeshes = new BABYLON.SmartArray(256);
  13863. _this._globalPosition = BABYLON.Vector3.Zero();
  13864. _this._refreshFrustumPlanes = true;
  13865. _this.getScene().addCamera(_this);
  13866. if (!_this.getScene().activeCamera) {
  13867. _this.getScene().activeCamera = _this;
  13868. }
  13869. _this.position = position;
  13870. return _this;
  13871. }
  13872. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13873. get: function () {
  13874. return Camera._PERSPECTIVE_CAMERA;
  13875. },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13880. get: function () {
  13881. return Camera._ORTHOGRAPHIC_CAMERA;
  13882. },
  13883. enumerable: true,
  13884. configurable: true
  13885. });
  13886. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13887. get: function () {
  13888. return Camera._FOVMODE_VERTICAL_FIXED;
  13889. },
  13890. enumerable: true,
  13891. configurable: true
  13892. });
  13893. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13894. get: function () {
  13895. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13901. get: function () {
  13902. return Camera._RIG_MODE_NONE;
  13903. },
  13904. enumerable: true,
  13905. configurable: true
  13906. });
  13907. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13908. get: function () {
  13909. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13915. get: function () {
  13916. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13917. },
  13918. enumerable: true,
  13919. configurable: true
  13920. });
  13921. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13922. get: function () {
  13923. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13924. },
  13925. enumerable: true,
  13926. configurable: true
  13927. });
  13928. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13929. get: function () {
  13930. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13931. },
  13932. enumerable: true,
  13933. configurable: true
  13934. });
  13935. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13936. get: function () {
  13937. return Camera._RIG_MODE_VR;
  13938. },
  13939. enumerable: true,
  13940. configurable: true
  13941. });
  13942. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13943. get: function () {
  13944. return Camera._RIG_MODE_WEBVR;
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. Camera.prototype.getClassName = function () {
  13950. return "Camera";
  13951. };
  13952. /**
  13953. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13954. */
  13955. Camera.prototype.toString = function (fullDetails) {
  13956. var ret = "Name: " + this.name;
  13957. ret += ", type: " + this.getClassName();
  13958. if (this.animations) {
  13959. for (var i = 0; i < this.animations.length; i++) {
  13960. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13961. }
  13962. }
  13963. if (fullDetails) {
  13964. }
  13965. return ret;
  13966. };
  13967. Object.defineProperty(Camera.prototype, "globalPosition", {
  13968. get: function () {
  13969. return this._globalPosition;
  13970. },
  13971. enumerable: true,
  13972. configurable: true
  13973. });
  13974. Camera.prototype.getActiveMeshes = function () {
  13975. return this._activeMeshes;
  13976. };
  13977. Camera.prototype.isActiveMesh = function (mesh) {
  13978. return (this._activeMeshes.indexOf(mesh) !== -1);
  13979. };
  13980. //Cache
  13981. Camera.prototype._initCache = function () {
  13982. _super.prototype._initCache.call(this);
  13983. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13984. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13985. this._cache.mode = undefined;
  13986. this._cache.minZ = undefined;
  13987. this._cache.maxZ = undefined;
  13988. this._cache.fov = undefined;
  13989. this._cache.fovMode = undefined;
  13990. this._cache.aspectRatio = undefined;
  13991. this._cache.orthoLeft = undefined;
  13992. this._cache.orthoRight = undefined;
  13993. this._cache.orthoBottom = undefined;
  13994. this._cache.orthoTop = undefined;
  13995. this._cache.renderWidth = undefined;
  13996. this._cache.renderHeight = undefined;
  13997. };
  13998. Camera.prototype._updateCache = function (ignoreParentClass) {
  13999. if (!ignoreParentClass) {
  14000. _super.prototype._updateCache.call(this);
  14001. }
  14002. var engine = this.getEngine();
  14003. this._cache.position.copyFrom(this.position);
  14004. this._cache.upVector.copyFrom(this.upVector);
  14005. this._cache.mode = this.mode;
  14006. this._cache.minZ = this.minZ;
  14007. this._cache.maxZ = this.maxZ;
  14008. this._cache.fov = this.fov;
  14009. this._cache.fovMode = this.fovMode;
  14010. this._cache.aspectRatio = engine.getAspectRatio(this);
  14011. this._cache.orthoLeft = this.orthoLeft;
  14012. this._cache.orthoRight = this.orthoRight;
  14013. this._cache.orthoBottom = this.orthoBottom;
  14014. this._cache.orthoTop = this.orthoTop;
  14015. this._cache.renderWidth = engine.getRenderWidth();
  14016. this._cache.renderHeight = engine.getRenderHeight();
  14017. };
  14018. Camera.prototype._updateFromScene = function () {
  14019. this.updateCache();
  14020. this.update();
  14021. };
  14022. // Synchronized
  14023. Camera.prototype._isSynchronized = function () {
  14024. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14025. };
  14026. Camera.prototype._isSynchronizedViewMatrix = function () {
  14027. if (!_super.prototype._isSynchronized.call(this))
  14028. return false;
  14029. return this._cache.position.equals(this.position)
  14030. && this._cache.upVector.equals(this.upVector)
  14031. && this.isSynchronizedWithParent();
  14032. };
  14033. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14034. var check = this._cache.mode === this.mode
  14035. && this._cache.minZ === this.minZ
  14036. && this._cache.maxZ === this.maxZ;
  14037. if (!check) {
  14038. return false;
  14039. }
  14040. var engine = this.getEngine();
  14041. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14042. check = this._cache.fov === this.fov
  14043. && this._cache.fovMode === this.fovMode
  14044. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14045. }
  14046. else {
  14047. check = this._cache.orthoLeft === this.orthoLeft
  14048. && this._cache.orthoRight === this.orthoRight
  14049. && this._cache.orthoBottom === this.orthoBottom
  14050. && this._cache.orthoTop === this.orthoTop
  14051. && this._cache.renderWidth === engine.getRenderWidth()
  14052. && this._cache.renderHeight === engine.getRenderHeight();
  14053. }
  14054. return check;
  14055. };
  14056. // Controls
  14057. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14058. };
  14059. Camera.prototype.detachControl = function (element) {
  14060. };
  14061. Camera.prototype.update = function () {
  14062. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14063. this._updateRigCameras();
  14064. }
  14065. this._checkInputs();
  14066. };
  14067. Camera.prototype._checkInputs = function () {
  14068. };
  14069. Object.defineProperty(Camera.prototype, "rigCameras", {
  14070. get: function () {
  14071. return this._rigCameras;
  14072. },
  14073. enumerable: true,
  14074. configurable: true
  14075. });
  14076. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14077. get: function () {
  14078. return this._rigPostProcess;
  14079. },
  14080. enumerable: true,
  14081. configurable: true
  14082. });
  14083. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14084. // invalidate framebuffer
  14085. if (this._postProcesses.length > 0) {
  14086. this._postProcesses[0].markTextureDirty();
  14087. }
  14088. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14089. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14090. var cam = this._rigCameras[i];
  14091. var rigPostProcess = cam._rigPostProcess;
  14092. // for VR rig, there does not have to be a post process
  14093. if (rigPostProcess) {
  14094. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14095. if (isPass) {
  14096. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14097. cam.isIntermediate = this._postProcesses.length === 0;
  14098. }
  14099. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14100. rigPostProcess.markTextureDirty();
  14101. }
  14102. else {
  14103. cam._postProcesses = this._postProcesses.slice(0);
  14104. }
  14105. }
  14106. };
  14107. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14108. if (insertAt === void 0) { insertAt = null; }
  14109. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14110. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14111. return 0;
  14112. }
  14113. if (insertAt == null || insertAt < 0) {
  14114. this._postProcesses.push(postProcess);
  14115. }
  14116. else {
  14117. this._postProcesses.splice(insertAt, 0, postProcess);
  14118. }
  14119. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14120. return this._postProcesses.indexOf(postProcess);
  14121. };
  14122. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14123. if (atIndices === void 0) { atIndices = null; }
  14124. var result = [];
  14125. var i;
  14126. var index;
  14127. if (!atIndices) {
  14128. var idx = this._postProcesses.indexOf(postProcess);
  14129. if (idx !== -1) {
  14130. this._postProcesses.splice(idx, 1);
  14131. }
  14132. }
  14133. else {
  14134. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14135. // iterate descending, so can just splice as we go
  14136. for (i = atIndices.length - 1; i >= 0; i--) {
  14137. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14138. result.push(i);
  14139. continue;
  14140. }
  14141. index = atIndices[i];
  14142. this._postProcesses.splice(index, 1);
  14143. }
  14144. }
  14145. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14146. return result;
  14147. };
  14148. Camera.prototype.getWorldMatrix = function () {
  14149. if (!this._worldMatrix) {
  14150. this._worldMatrix = BABYLON.Matrix.Identity();
  14151. }
  14152. var viewMatrix = this.getViewMatrix();
  14153. viewMatrix.invertToRef(this._worldMatrix);
  14154. return this._worldMatrix;
  14155. };
  14156. Camera.prototype._getViewMatrix = function () {
  14157. return BABYLON.Matrix.Identity();
  14158. };
  14159. Camera.prototype.getViewMatrix = function (force) {
  14160. this._computedViewMatrix = this._computeViewMatrix(force);
  14161. if (!force && this._isSynchronizedViewMatrix()) {
  14162. return this._computedViewMatrix;
  14163. }
  14164. this._refreshFrustumPlanes = true;
  14165. if (!this.parent || !this.parent.getWorldMatrix) {
  14166. this._globalPosition.copyFrom(this.position);
  14167. }
  14168. else {
  14169. if (!this._worldMatrix) {
  14170. this._worldMatrix = BABYLON.Matrix.Identity();
  14171. }
  14172. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14173. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14174. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14175. this._computedViewMatrix.invert();
  14176. this._markSyncedWithParent();
  14177. }
  14178. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14179. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14180. }
  14181. this._currentRenderId = this.getScene().getRenderId();
  14182. return this._computedViewMatrix;
  14183. };
  14184. Camera.prototype._computeViewMatrix = function (force) {
  14185. if (!force && this._isSynchronizedViewMatrix()) {
  14186. return this._computedViewMatrix;
  14187. }
  14188. this._computedViewMatrix = this._getViewMatrix();
  14189. this._currentRenderId = this.getScene().getRenderId();
  14190. return this._computedViewMatrix;
  14191. };
  14192. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14193. this._doNotComputeProjectionMatrix = true;
  14194. if (projection !== undefined) {
  14195. this._projectionMatrix = projection;
  14196. }
  14197. };
  14198. ;
  14199. Camera.prototype.unfreezeProjectionMatrix = function () {
  14200. this._doNotComputeProjectionMatrix = false;
  14201. };
  14202. ;
  14203. Camera.prototype.getProjectionMatrix = function (force) {
  14204. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14205. return this._projectionMatrix;
  14206. }
  14207. this._refreshFrustumPlanes = true;
  14208. var engine = this.getEngine();
  14209. var scene = this.getScene();
  14210. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14211. if (this.minZ <= 0) {
  14212. this.minZ = 0.1;
  14213. }
  14214. if (scene.useRightHandedSystem) {
  14215. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14216. }
  14217. else {
  14218. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14219. }
  14220. return this._projectionMatrix;
  14221. }
  14222. var halfWidth = engine.getRenderWidth() / 2.0;
  14223. var halfHeight = engine.getRenderHeight() / 2.0;
  14224. if (scene.useRightHandedSystem) {
  14225. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14226. }
  14227. else {
  14228. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14229. }
  14230. return this._projectionMatrix;
  14231. };
  14232. Camera.prototype.getTranformationMatrix = function () {
  14233. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14234. return this._transformMatrix;
  14235. };
  14236. Camera.prototype.updateFrustumPlanes = function () {
  14237. if (!this._refreshFrustumPlanes) {
  14238. return;
  14239. }
  14240. this.getTranformationMatrix();
  14241. if (!this._frustumPlanes) {
  14242. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14243. }
  14244. else {
  14245. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14246. }
  14247. this._refreshFrustumPlanes = false;
  14248. };
  14249. Camera.prototype.isInFrustum = function (target) {
  14250. this.updateFrustumPlanes();
  14251. return target.isInFrustum(this._frustumPlanes);
  14252. };
  14253. Camera.prototype.isCompletelyInFrustum = function (target) {
  14254. this.updateFrustumPlanes();
  14255. return target.isCompletelyInFrustum(this._frustumPlanes);
  14256. };
  14257. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14258. if (length === void 0) { length = 100; }
  14259. if (!transform) {
  14260. transform = this.getWorldMatrix();
  14261. }
  14262. if (!origin) {
  14263. origin = this.position;
  14264. }
  14265. var forward = new BABYLON.Vector3(0, 0, 1);
  14266. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14267. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14268. return new BABYLON.Ray(origin, direction, length);
  14269. };
  14270. Camera.prototype.dispose = function () {
  14271. // Animations
  14272. this.getScene().stopAnimation(this);
  14273. // Remove from scene
  14274. this.getScene().removeCamera(this);
  14275. while (this._rigCameras.length > 0) {
  14276. this._rigCameras.pop().dispose();
  14277. }
  14278. // Postprocesses
  14279. var i = this._postProcesses.length;
  14280. while (--i >= 0) {
  14281. this._postProcesses[i].dispose(this);
  14282. }
  14283. _super.prototype.dispose.call(this);
  14284. };
  14285. Object.defineProperty(Camera.prototype, "leftCamera", {
  14286. // ---- Camera rigs section ----
  14287. get: function () {
  14288. if (this._rigCameras.length < 1) {
  14289. return undefined;
  14290. }
  14291. return this._rigCameras[0];
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(Camera.prototype, "rightCamera", {
  14297. get: function () {
  14298. if (this._rigCameras.length < 2) {
  14299. return undefined;
  14300. }
  14301. return this._rigCameras[1];
  14302. },
  14303. enumerable: true,
  14304. configurable: true
  14305. });
  14306. Camera.prototype.getLeftTarget = function () {
  14307. if (this._rigCameras.length < 1) {
  14308. return undefined;
  14309. }
  14310. return this._rigCameras[0].getTarget();
  14311. };
  14312. Camera.prototype.getRightTarget = function () {
  14313. if (this._rigCameras.length < 2) {
  14314. return undefined;
  14315. }
  14316. return this._rigCameras[1].getTarget();
  14317. };
  14318. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14319. while (this._rigCameras.length > 0) {
  14320. this._rigCameras.pop().dispose();
  14321. }
  14322. this.cameraRigMode = mode;
  14323. this._cameraRigParams = {};
  14324. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14325. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14326. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14327. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14328. // create the rig cameras, unless none
  14329. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14330. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14331. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14332. }
  14333. switch (this.cameraRigMode) {
  14334. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14335. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14336. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14337. break;
  14338. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14339. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14340. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14341. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14342. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14343. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14344. break;
  14345. case Camera.RIG_MODE_VR:
  14346. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14347. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14348. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14349. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14350. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14351. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14352. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14353. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14354. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14355. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14356. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14357. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14358. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14359. if (metrics.compensateDistortion) {
  14360. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14361. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14362. }
  14363. break;
  14364. case Camera.RIG_MODE_WEBVR:
  14365. if (rigParams.vrDisplay) {
  14366. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14367. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14368. //Left eye
  14369. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14370. this._rigCameras[0].setCameraRigParameter("left", true);
  14371. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14372. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14373. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14374. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14375. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14376. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14377. this._rigCameras[0].parent = this;
  14378. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14379. //Right eye
  14380. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14381. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14382. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14383. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14384. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14385. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14386. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14387. this._rigCameras[1].parent = this;
  14388. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14389. }
  14390. break;
  14391. }
  14392. this._cascadePostProcessesToRigCams();
  14393. this.
  14394. update();
  14395. };
  14396. Camera.prototype._getVRProjectionMatrix = function () {
  14397. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14398. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14399. return this._projectionMatrix;
  14400. };
  14401. Camera.prototype._updateCameraRotationMatrix = function () {
  14402. //Here for WebVR
  14403. };
  14404. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14405. //Here for WebVR
  14406. };
  14407. /**
  14408. * This function MUST be overwritten by the different WebVR cameras available.
  14409. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14410. */
  14411. Camera.prototype._getWebVRProjectionMatrix = function () {
  14412. return BABYLON.Matrix.Identity();
  14413. };
  14414. /**
  14415. * This function MUST be overwritten by the different WebVR cameras available.
  14416. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14417. */
  14418. Camera.prototype._getWebVRViewMatrix = function () {
  14419. return BABYLON.Matrix.Identity();
  14420. };
  14421. Camera.prototype.setCameraRigParameter = function (name, value) {
  14422. if (!this._cameraRigParams) {
  14423. this._cameraRigParams = {};
  14424. }
  14425. this._cameraRigParams[name] = value;
  14426. //provisionnally:
  14427. if (name === "interaxialDistance") {
  14428. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14429. }
  14430. };
  14431. /**
  14432. * needs to be overridden by children so sub has required properties to be copied
  14433. */
  14434. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14435. return null;
  14436. };
  14437. /**
  14438. * May need to be overridden by children
  14439. */
  14440. Camera.prototype._updateRigCameras = function () {
  14441. for (var i = 0; i < this._rigCameras.length; i++) {
  14442. this._rigCameras[i].minZ = this.minZ;
  14443. this._rigCameras[i].maxZ = this.maxZ;
  14444. this._rigCameras[i].fov = this.fov;
  14445. }
  14446. // only update viewport when ANAGLYPH
  14447. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14448. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14449. }
  14450. };
  14451. Camera.prototype._setupInputs = function () {
  14452. };
  14453. Camera.prototype.serialize = function () {
  14454. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14455. // Type
  14456. serializationObject.type = this.getClassName();
  14457. // Parent
  14458. if (this.parent) {
  14459. serializationObject.parentId = this.parent.id;
  14460. }
  14461. if (this.inputs) {
  14462. this.inputs.serialize(serializationObject);
  14463. }
  14464. // Animations
  14465. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14466. serializationObject.ranges = this.serializeAnimationRanges();
  14467. return serializationObject;
  14468. };
  14469. Camera.prototype.clone = function (name) {
  14470. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14471. };
  14472. Camera.prototype.getDirection = function (localAxis) {
  14473. var result = BABYLON.Vector3.Zero();
  14474. this.getDirectionToRef(localAxis, result);
  14475. return result;
  14476. };
  14477. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14478. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14479. };
  14480. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14481. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14482. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14483. switch (type) {
  14484. case "ArcRotateCamera":
  14485. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14486. case "DeviceOrientationCamera":
  14487. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14488. case "FollowCamera":
  14489. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14490. case "ArcFollowCamera":
  14491. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14492. case "GamepadCamera":
  14493. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14494. case "TouchCamera":
  14495. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14496. case "VirtualJoysticksCamera":
  14497. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14498. case "WebVRFreeCamera":
  14499. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14500. case "WebVRGamepadCamera":
  14501. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14502. case "VRDeviceOrientationFreeCamera":
  14503. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14504. case "VRDeviceOrientationGamepadCamera":
  14505. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14506. case "AnaglyphArcRotateCamera":
  14507. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14508. case "AnaglyphFreeCamera":
  14509. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14510. case "AnaglyphGamepadCamera":
  14511. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14512. case "AnaglyphUniversalCamera":
  14513. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14514. case "StereoscopicArcRotateCamera":
  14515. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14516. case "StereoscopicFreeCamera":
  14517. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14518. case "StereoscopicGamepadCamera":
  14519. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14520. case "StereoscopicUniversalCamera":
  14521. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14522. case "FreeCamera":
  14523. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14524. default:
  14525. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14526. }
  14527. };
  14528. Camera.Parse = function (parsedCamera, scene) {
  14529. var type = parsedCamera.type;
  14530. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14531. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14532. // Parent
  14533. if (parsedCamera.parentId) {
  14534. camera._waitingParentId = parsedCamera.parentId;
  14535. }
  14536. //If camera has an input manager, let it parse inputs settings
  14537. if (camera.inputs) {
  14538. camera.inputs.parse(parsedCamera);
  14539. camera._setupInputs();
  14540. }
  14541. // Target
  14542. if (parsedCamera.target) {
  14543. if (camera.setTarget) {
  14544. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14545. }
  14546. }
  14547. // Apply 3d rig, when found
  14548. if (parsedCamera.cameraRigMode) {
  14549. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14550. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14551. }
  14552. // Animations
  14553. if (parsedCamera.animations) {
  14554. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14555. var parsedAnimation = parsedCamera.animations[animationIndex];
  14556. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14557. }
  14558. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14559. }
  14560. if (parsedCamera.autoAnimate) {
  14561. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14562. }
  14563. return camera;
  14564. };
  14565. return Camera;
  14566. }(BABYLON.Node));
  14567. // Statics
  14568. Camera._PERSPECTIVE_CAMERA = 0;
  14569. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14570. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14571. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14572. Camera._RIG_MODE_NONE = 0;
  14573. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14574. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14575. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14576. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14577. Camera._RIG_MODE_VR = 20;
  14578. Camera._RIG_MODE_WEBVR = 21;
  14579. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14580. __decorate([
  14581. BABYLON.serializeAsVector3()
  14582. ], Camera.prototype, "position", void 0);
  14583. __decorate([
  14584. BABYLON.serializeAsVector3()
  14585. ], Camera.prototype, "upVector", void 0);
  14586. __decorate([
  14587. BABYLON.serialize()
  14588. ], Camera.prototype, "orthoLeft", void 0);
  14589. __decorate([
  14590. BABYLON.serialize()
  14591. ], Camera.prototype, "orthoRight", void 0);
  14592. __decorate([
  14593. BABYLON.serialize()
  14594. ], Camera.prototype, "orthoBottom", void 0);
  14595. __decorate([
  14596. BABYLON.serialize()
  14597. ], Camera.prototype, "orthoTop", void 0);
  14598. __decorate([
  14599. BABYLON.serialize()
  14600. ], Camera.prototype, "fov", void 0);
  14601. __decorate([
  14602. BABYLON.serialize()
  14603. ], Camera.prototype, "minZ", void 0);
  14604. __decorate([
  14605. BABYLON.serialize()
  14606. ], Camera.prototype, "maxZ", void 0);
  14607. __decorate([
  14608. BABYLON.serialize()
  14609. ], Camera.prototype, "inertia", void 0);
  14610. __decorate([
  14611. BABYLON.serialize()
  14612. ], Camera.prototype, "mode", void 0);
  14613. __decorate([
  14614. BABYLON.serialize()
  14615. ], Camera.prototype, "layerMask", void 0);
  14616. __decorate([
  14617. BABYLON.serialize()
  14618. ], Camera.prototype, "fovMode", void 0);
  14619. __decorate([
  14620. BABYLON.serialize()
  14621. ], Camera.prototype, "cameraRigMode", void 0);
  14622. __decorate([
  14623. BABYLON.serialize()
  14624. ], Camera.prototype, "interaxialDistance", void 0);
  14625. __decorate([
  14626. BABYLON.serialize()
  14627. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14628. BABYLON.Camera = Camera;
  14629. })(BABYLON || (BABYLON = {}));
  14630. //# sourceMappingURL=babylon.camera.js.map
  14631. var BABYLON;
  14632. (function (BABYLON) {
  14633. var RenderingManager = (function () {
  14634. function RenderingManager(scene) {
  14635. this._renderingGroups = new Array();
  14636. this._autoClearDepthStencil = {};
  14637. this._customOpaqueSortCompareFn = {};
  14638. this._customAlphaTestSortCompareFn = {};
  14639. this._customTransparentSortCompareFn = {};
  14640. this._renderinGroupInfo = null;
  14641. this._scene = scene;
  14642. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14643. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14644. }
  14645. }
  14646. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14647. if (depth === void 0) { depth = true; }
  14648. if (stencil === void 0) { stencil = true; }
  14649. if (this._depthStencilBufferAlreadyCleaned) {
  14650. return;
  14651. }
  14652. this._scene.getEngine().clear(null, false, depth, stencil);
  14653. this._depthStencilBufferAlreadyCleaned = true;
  14654. };
  14655. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14656. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14657. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14658. var info = null;
  14659. if (observable) {
  14660. if (!this._renderinGroupInfo) {
  14661. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14662. }
  14663. info = this._renderinGroupInfo;
  14664. info.scene = this._scene;
  14665. info.camera = this._scene.activeCamera;
  14666. }
  14667. // Dispatch sprites
  14668. if (renderSprites) {
  14669. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14670. var manager = this._scene.spriteManagers[index];
  14671. this.dispatchSprites(manager);
  14672. }
  14673. }
  14674. // Render
  14675. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14676. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14677. var renderingGroup = this._renderingGroups[index];
  14678. if (!renderingGroup && !observable)
  14679. continue;
  14680. this._currentIndex = index;
  14681. var renderingGroupMask = 0;
  14682. // Fire PRECLEAR stage
  14683. if (observable) {
  14684. renderingGroupMask = Math.pow(2, index);
  14685. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14686. info.renderingGroupId = index;
  14687. observable.notifyObservers(info, renderingGroupMask);
  14688. }
  14689. // Clear depth/stencil if needed
  14690. if (RenderingManager.AUTOCLEAR) {
  14691. var autoClear = this._autoClearDepthStencil[index];
  14692. if (autoClear && autoClear.autoClear) {
  14693. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14694. }
  14695. }
  14696. if (observable) {
  14697. // Fire PREOPAQUE stage
  14698. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14699. observable.notifyObservers(info, renderingGroupMask);
  14700. // Fire PRETRANSPARENT stage
  14701. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14702. observable.notifyObservers(info, renderingGroupMask);
  14703. }
  14704. if (renderingGroup)
  14705. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14706. // Fire POSTTRANSPARENT stage
  14707. if (observable) {
  14708. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14709. observable.notifyObservers(info, renderingGroupMask);
  14710. }
  14711. }
  14712. };
  14713. RenderingManager.prototype.reset = function () {
  14714. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14715. var renderingGroup = this._renderingGroups[index];
  14716. if (renderingGroup) {
  14717. renderingGroup.prepare();
  14718. }
  14719. }
  14720. };
  14721. RenderingManager.prototype.dispose = function () {
  14722. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14723. var renderingGroup = this._renderingGroups[index];
  14724. if (renderingGroup) {
  14725. renderingGroup.dispose();
  14726. }
  14727. }
  14728. this._renderingGroups.length = 0;
  14729. };
  14730. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14731. if (!this._renderingGroups[renderingGroupId]) {
  14732. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14733. }
  14734. };
  14735. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14736. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14737. this._prepareRenderingGroup(renderingGroupId);
  14738. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14739. };
  14740. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14741. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14742. this._prepareRenderingGroup(renderingGroupId);
  14743. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14744. };
  14745. RenderingManager.prototype.dispatch = function (subMesh) {
  14746. var mesh = subMesh.getMesh();
  14747. var renderingGroupId = mesh.renderingGroupId || 0;
  14748. this._prepareRenderingGroup(renderingGroupId);
  14749. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14750. };
  14751. /**
  14752. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14753. * This allowed control for front to back rendering or reversly depending of the special needs.
  14754. *
  14755. * @param renderingGroupId The rendering group id corresponding to its index
  14756. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14757. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14758. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14759. */
  14760. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14761. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14762. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14763. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14764. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14765. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14766. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14767. if (this._renderingGroups[renderingGroupId]) {
  14768. var group = this._renderingGroups[renderingGroupId];
  14769. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14770. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14771. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14772. }
  14773. };
  14774. /**
  14775. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14776. *
  14777. * @param renderingGroupId The rendering group id corresponding to its index
  14778. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14779. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14780. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14781. */
  14782. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14783. if (depth === void 0) { depth = true; }
  14784. if (stencil === void 0) { stencil = true; }
  14785. this._autoClearDepthStencil[renderingGroupId] = {
  14786. autoClear: autoClearDepthStencil,
  14787. depth: depth,
  14788. stencil: stencil
  14789. };
  14790. };
  14791. return RenderingManager;
  14792. }());
  14793. /**
  14794. * The max id used for rendering groups (not included)
  14795. */
  14796. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14797. /**
  14798. * The min id used for rendering groups (included)
  14799. */
  14800. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14801. /**
  14802. * Used to globally prevent autoclearing scenes.
  14803. */
  14804. RenderingManager.AUTOCLEAR = true;
  14805. BABYLON.RenderingManager = RenderingManager;
  14806. })(BABYLON || (BABYLON = {}));
  14807. //# sourceMappingURL=babylon.renderingManager.js.map
  14808. var BABYLON;
  14809. (function (BABYLON) {
  14810. var RenderingGroup = (function () {
  14811. /**
  14812. * Creates a new rendering group.
  14813. * @param index The rendering group index
  14814. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14815. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14816. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14817. */
  14818. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14819. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14820. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14821. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14822. this.index = index;
  14823. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14824. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14825. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14826. this._particleSystems = new BABYLON.SmartArray(256);
  14827. this._spriteManagers = new BABYLON.SmartArray(256);
  14828. this._edgesRenderers = new BABYLON.SmartArray(16);
  14829. this._scene = scene;
  14830. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14831. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14832. this.transparentSortCompareFn = transparentSortCompareFn;
  14833. }
  14834. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14835. /**
  14836. * Set the opaque sort comparison function.
  14837. * If null the sub meshes will be render in the order they were created
  14838. */
  14839. set: function (value) {
  14840. this._opaqueSortCompareFn = value;
  14841. if (value) {
  14842. this._renderOpaque = this.renderOpaqueSorted;
  14843. }
  14844. else {
  14845. this._renderOpaque = RenderingGroup.renderUnsorted;
  14846. }
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14852. /**
  14853. * Set the alpha test sort comparison function.
  14854. * If null the sub meshes will be render in the order they were created
  14855. */
  14856. set: function (value) {
  14857. this._alphaTestSortCompareFn = value;
  14858. if (value) {
  14859. this._renderAlphaTest = this.renderAlphaTestSorted;
  14860. }
  14861. else {
  14862. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14863. }
  14864. },
  14865. enumerable: true,
  14866. configurable: true
  14867. });
  14868. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14869. /**
  14870. * Set the transparent sort comparison function.
  14871. * If null the sub meshes will be render in the order they were created
  14872. */
  14873. set: function (value) {
  14874. if (value) {
  14875. this._transparentSortCompareFn = value;
  14876. }
  14877. else {
  14878. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14879. }
  14880. this._renderTransparent = this.renderTransparentSorted;
  14881. },
  14882. enumerable: true,
  14883. configurable: true
  14884. });
  14885. /**
  14886. * Render all the sub meshes contained in the group.
  14887. * @param customRenderFunction Used to override the default render behaviour of the group.
  14888. * @returns true if rendered some submeshes.
  14889. */
  14890. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14891. if (customRenderFunction) {
  14892. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14893. return;
  14894. }
  14895. var engine = this._scene.getEngine();
  14896. // Opaque
  14897. if (this._opaqueSubMeshes.length !== 0) {
  14898. this._renderOpaque(this._opaqueSubMeshes);
  14899. }
  14900. // Alpha test
  14901. if (this._alphaTestSubMeshes.length !== 0) {
  14902. engine.setAlphaTesting(true);
  14903. this._renderAlphaTest(this._alphaTestSubMeshes);
  14904. engine.setAlphaTesting(false);
  14905. }
  14906. var stencilState = engine.getStencilBuffer();
  14907. engine.setStencilBuffer(false);
  14908. // Sprites
  14909. if (renderSprites) {
  14910. this._renderSprites();
  14911. }
  14912. // Particles
  14913. if (renderParticles) {
  14914. this._renderParticles(activeMeshes);
  14915. }
  14916. if (this.onBeforeTransparentRendering) {
  14917. this.onBeforeTransparentRendering();
  14918. }
  14919. // Transparent
  14920. if (this._transparentSubMeshes.length !== 0) {
  14921. this._renderTransparent(this._transparentSubMeshes);
  14922. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14923. }
  14924. engine.setStencilBuffer(stencilState);
  14925. // Edges
  14926. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14927. this._edgesRenderers.data[edgesRendererIndex].render();
  14928. }
  14929. };
  14930. /**
  14931. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14932. * @param subMeshes The submeshes to render
  14933. */
  14934. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14935. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14936. };
  14937. /**
  14938. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14939. * @param subMeshes The submeshes to render
  14940. */
  14941. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14942. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14943. };
  14944. /**
  14945. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14946. * @param subMeshes The submeshes to render
  14947. */
  14948. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14949. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14950. };
  14951. /**
  14952. * Renders the submeshes in a specified order.
  14953. * @param subMeshes The submeshes to sort before render
  14954. * @param sortCompareFn The comparison function use to sort
  14955. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14956. * @param transparent Specifies to activate blending if true
  14957. */
  14958. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14959. var subIndex = 0;
  14960. var subMesh;
  14961. for (; subIndex < subMeshes.length; subIndex++) {
  14962. subMesh = subMeshes.data[subIndex];
  14963. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14964. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14965. }
  14966. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14967. sortedArray.sort(sortCompareFn);
  14968. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14969. subMesh = sortedArray[subIndex];
  14970. subMesh.render(transparent);
  14971. }
  14972. };
  14973. /**
  14974. * Renders the submeshes in the order they were dispatched (no sort applied).
  14975. * @param subMeshes The submeshes to render
  14976. */
  14977. RenderingGroup.renderUnsorted = function (subMeshes) {
  14978. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14979. var submesh = subMeshes.data[subIndex];
  14980. submesh.render(false);
  14981. }
  14982. };
  14983. /**
  14984. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14985. * are rendered back to front if in the same alpha index.
  14986. *
  14987. * @param a The first submesh
  14988. * @param b The second submesh
  14989. * @returns The result of the comparison
  14990. */
  14991. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14992. // Alpha index first
  14993. if (a._alphaIndex > b._alphaIndex) {
  14994. return 1;
  14995. }
  14996. if (a._alphaIndex < b._alphaIndex) {
  14997. return -1;
  14998. }
  14999. // Then distance to camera
  15000. return RenderingGroup.backToFrontSortCompare(a, b);
  15001. };
  15002. /**
  15003. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15004. * are rendered back to front.
  15005. *
  15006. * @param a The first submesh
  15007. * @param b The second submesh
  15008. * @returns The result of the comparison
  15009. */
  15010. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15011. // Then distance to camera
  15012. if (a._distanceToCamera < b._distanceToCamera) {
  15013. return 1;
  15014. }
  15015. if (a._distanceToCamera > b._distanceToCamera) {
  15016. return -1;
  15017. }
  15018. return 0;
  15019. };
  15020. /**
  15021. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15022. * are rendered front to back (prevent overdraw).
  15023. *
  15024. * @param a The first submesh
  15025. * @param b The second submesh
  15026. * @returns The result of the comparison
  15027. */
  15028. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15029. // Then distance to camera
  15030. if (a._distanceToCamera < b._distanceToCamera) {
  15031. return -1;
  15032. }
  15033. if (a._distanceToCamera > b._distanceToCamera) {
  15034. return 1;
  15035. }
  15036. return 0;
  15037. };
  15038. /**
  15039. * Resets the different lists of submeshes to prepare a new frame.
  15040. */
  15041. RenderingGroup.prototype.prepare = function () {
  15042. this._opaqueSubMeshes.reset();
  15043. this._transparentSubMeshes.reset();
  15044. this._alphaTestSubMeshes.reset();
  15045. this._particleSystems.reset();
  15046. this._spriteManagers.reset();
  15047. this._edgesRenderers.reset();
  15048. };
  15049. RenderingGroup.prototype.dispose = function () {
  15050. this._opaqueSubMeshes.dispose();
  15051. this._transparentSubMeshes.dispose();
  15052. this._alphaTestSubMeshes.dispose();
  15053. this._particleSystems.dispose();
  15054. this._spriteManagers.dispose();
  15055. this._edgesRenderers.dispose();
  15056. };
  15057. /**
  15058. * Inserts the submesh in its correct queue depending on its material.
  15059. * @param subMesh The submesh to dispatch
  15060. */
  15061. RenderingGroup.prototype.dispatch = function (subMesh) {
  15062. var material = subMesh.getMaterial();
  15063. var mesh = subMesh.getMesh();
  15064. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15065. this._transparentSubMeshes.push(subMesh);
  15066. }
  15067. else if (material.needAlphaTesting()) {
  15068. this._alphaTestSubMeshes.push(subMesh);
  15069. }
  15070. else {
  15071. this._opaqueSubMeshes.push(subMesh); // Opaque
  15072. }
  15073. if (mesh._edgesRenderer) {
  15074. this._edgesRenderers.push(mesh._edgesRenderer);
  15075. }
  15076. };
  15077. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15078. this._spriteManagers.push(spriteManager);
  15079. };
  15080. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15081. this._particleSystems.push(particleSystem);
  15082. };
  15083. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15084. if (this._particleSystems.length === 0) {
  15085. return;
  15086. }
  15087. // Particles
  15088. var activeCamera = this._scene.activeCamera;
  15089. this._scene._particlesDuration.beginMonitoring();
  15090. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15091. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15092. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15093. continue;
  15094. }
  15095. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15096. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15097. }
  15098. }
  15099. this._scene._particlesDuration.endMonitoring(false);
  15100. };
  15101. RenderingGroup.prototype._renderSprites = function () {
  15102. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15103. return;
  15104. }
  15105. // Sprites
  15106. var activeCamera = this._scene.activeCamera;
  15107. this._scene._spritesDuration.beginMonitoring();
  15108. for (var id = 0; id < this._spriteManagers.length; id++) {
  15109. var spriteManager = this._spriteManagers.data[id];
  15110. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15111. spriteManager.render();
  15112. }
  15113. }
  15114. this._scene._spritesDuration.endMonitoring(false);
  15115. };
  15116. return RenderingGroup;
  15117. }());
  15118. BABYLON.RenderingGroup = RenderingGroup;
  15119. })(BABYLON || (BABYLON = {}));
  15120. //# sourceMappingURL=babylon.renderingGroup.js.map
  15121. var BABYLON;
  15122. (function (BABYLON) {
  15123. var ClickInfo = (function () {
  15124. function ClickInfo() {
  15125. this._singleClick = false;
  15126. this._doubleClick = false;
  15127. this._hasSwiped = false;
  15128. this._ignore = false;
  15129. }
  15130. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15131. get: function () {
  15132. return this._singleClick;
  15133. },
  15134. set: function (b) {
  15135. this._singleClick = b;
  15136. },
  15137. enumerable: true,
  15138. configurable: true
  15139. });
  15140. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15141. get: function () {
  15142. return this._doubleClick;
  15143. },
  15144. set: function (b) {
  15145. this._doubleClick = b;
  15146. },
  15147. enumerable: true,
  15148. configurable: true
  15149. });
  15150. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15151. get: function () {
  15152. return this._hasSwiped;
  15153. },
  15154. set: function (b) {
  15155. this._hasSwiped = b;
  15156. },
  15157. enumerable: true,
  15158. configurable: true
  15159. });
  15160. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15161. get: function () {
  15162. return this._ignore;
  15163. },
  15164. set: function (b) {
  15165. this._ignore = b;
  15166. },
  15167. enumerable: true,
  15168. configurable: true
  15169. });
  15170. return ClickInfo;
  15171. }());
  15172. var PointerEventTypes = (function () {
  15173. function PointerEventTypes() {
  15174. }
  15175. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15176. get: function () {
  15177. return PointerEventTypes._POINTERDOWN;
  15178. },
  15179. enumerable: true,
  15180. configurable: true
  15181. });
  15182. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15183. get: function () {
  15184. return PointerEventTypes._POINTERUP;
  15185. },
  15186. enumerable: true,
  15187. configurable: true
  15188. });
  15189. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15190. get: function () {
  15191. return PointerEventTypes._POINTERMOVE;
  15192. },
  15193. enumerable: true,
  15194. configurable: true
  15195. });
  15196. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15197. get: function () {
  15198. return PointerEventTypes._POINTERWHEEL;
  15199. },
  15200. enumerable: true,
  15201. configurable: true
  15202. });
  15203. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15204. get: function () {
  15205. return PointerEventTypes._POINTERPICK;
  15206. },
  15207. enumerable: true,
  15208. configurable: true
  15209. });
  15210. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15211. get: function () {
  15212. return PointerEventTypes._POINTERTAP;
  15213. },
  15214. enumerable: true,
  15215. configurable: true
  15216. });
  15217. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15218. get: function () {
  15219. return PointerEventTypes._POINTERDOUBLETAP;
  15220. },
  15221. enumerable: true,
  15222. configurable: true
  15223. });
  15224. return PointerEventTypes;
  15225. }());
  15226. PointerEventTypes._POINTERDOWN = 0x01;
  15227. PointerEventTypes._POINTERUP = 0x02;
  15228. PointerEventTypes._POINTERMOVE = 0x04;
  15229. PointerEventTypes._POINTERWHEEL = 0x08;
  15230. PointerEventTypes._POINTERPICK = 0x10;
  15231. PointerEventTypes._POINTERTAP = 0x20;
  15232. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15233. BABYLON.PointerEventTypes = PointerEventTypes;
  15234. var PointerInfoBase = (function () {
  15235. function PointerInfoBase(type, event) {
  15236. this.type = type;
  15237. this.event = event;
  15238. }
  15239. return PointerInfoBase;
  15240. }());
  15241. BABYLON.PointerInfoBase = PointerInfoBase;
  15242. /**
  15243. * This class is used to store pointer related info for the onPrePointerObservable event.
  15244. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15245. */
  15246. var PointerInfoPre = (function (_super) {
  15247. __extends(PointerInfoPre, _super);
  15248. function PointerInfoPre(type, event, localX, localY) {
  15249. var _this = _super.call(this, type, event) || this;
  15250. _this.skipOnPointerObservable = false;
  15251. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15252. return _this;
  15253. }
  15254. return PointerInfoPre;
  15255. }(PointerInfoBase));
  15256. BABYLON.PointerInfoPre = PointerInfoPre;
  15257. /**
  15258. * This type contains all the data related to a pointer event in Babylon.js.
  15259. * 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.
  15260. */
  15261. var PointerInfo = (function (_super) {
  15262. __extends(PointerInfo, _super);
  15263. function PointerInfo(type, event, pickInfo) {
  15264. var _this = _super.call(this, type, event) || this;
  15265. _this.pickInfo = pickInfo;
  15266. return _this;
  15267. }
  15268. return PointerInfo;
  15269. }(PointerInfoBase));
  15270. BABYLON.PointerInfo = PointerInfo;
  15271. /**
  15272. * This class is used by the onRenderingGroupObservable
  15273. */
  15274. var RenderingGroupInfo = (function () {
  15275. function RenderingGroupInfo() {
  15276. }
  15277. return RenderingGroupInfo;
  15278. }());
  15279. /**
  15280. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15281. * This stage will be fired no matter what
  15282. */
  15283. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15284. /**
  15285. * Called before opaque object are rendered.
  15286. * This stage will be fired only if there's 3D Opaque content to render
  15287. */
  15288. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15289. /**
  15290. * Called after the opaque objects are rendered and before the transparent ones
  15291. * This stage will be fired only if there's 3D transparent content to render
  15292. */
  15293. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15294. /**
  15295. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15296. * This stage will be fired no matter what
  15297. */
  15298. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15299. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15300. /**
  15301. * Represents a scene to be rendered by the engine.
  15302. * @see http://doc.babylonjs.com/page.php?p=21911
  15303. */
  15304. var Scene = (function () {
  15305. /**
  15306. * @constructor
  15307. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15308. */
  15309. function Scene(engine) {
  15310. // Members
  15311. this.autoClear = true;
  15312. this.autoClearDepthAndStencil = true;
  15313. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15314. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15315. this.forceWireframe = false;
  15316. this._forcePointsCloud = false;
  15317. this.forceShowBoundingBoxes = false;
  15318. this.animationsEnabled = true;
  15319. this.constantlyUpdateMeshUnderPointer = false;
  15320. this.hoverCursor = "pointer";
  15321. // Metadata
  15322. this.metadata = null;
  15323. // Events
  15324. /**
  15325. * An event triggered when the scene is disposed.
  15326. * @type {BABYLON.Observable}
  15327. */
  15328. this.onDisposeObservable = new BABYLON.Observable();
  15329. /**
  15330. * An event triggered before rendering the scene
  15331. * @type {BABYLON.Observable}
  15332. */
  15333. this.onBeforeRenderObservable = new BABYLON.Observable();
  15334. /**
  15335. * An event triggered after rendering the scene
  15336. * @type {BABYLON.Observable}
  15337. */
  15338. this.onAfterRenderObservable = new BABYLON.Observable();
  15339. /**
  15340. * An event triggered when the scene is ready
  15341. * @type {BABYLON.Observable}
  15342. */
  15343. this.onReadyObservable = new BABYLON.Observable();
  15344. /**
  15345. * An event triggered before rendering a camera
  15346. * @type {BABYLON.Observable}
  15347. */
  15348. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15349. /**
  15350. * An event triggered after rendering a camera
  15351. * @type {BABYLON.Observable}
  15352. */
  15353. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15354. /**
  15355. * An event triggered when a camera is created
  15356. * @type {BABYLON.Observable}
  15357. */
  15358. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15359. /**
  15360. * An event triggered when a camera is removed
  15361. * @type {BABYLON.Observable}
  15362. */
  15363. this.onCameraRemovedObservable = new BABYLON.Observable();
  15364. /**
  15365. * An event triggered when a light is created
  15366. * @type {BABYLON.Observable}
  15367. */
  15368. this.onNewLightAddedObservable = new BABYLON.Observable();
  15369. /**
  15370. * An event triggered when a light is removed
  15371. * @type {BABYLON.Observable}
  15372. */
  15373. this.onLightRemovedObservable = new BABYLON.Observable();
  15374. /**
  15375. * An event triggered when a geometry is created
  15376. * @type {BABYLON.Observable}
  15377. */
  15378. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15379. /**
  15380. * An event triggered when a geometry is removed
  15381. * @type {BABYLON.Observable}
  15382. */
  15383. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15384. /**
  15385. * An event triggered when a mesh is created
  15386. * @type {BABYLON.Observable}
  15387. */
  15388. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15389. /**
  15390. * An event triggered when a mesh is removed
  15391. * @type {BABYLON.Observable}
  15392. */
  15393. this.onMeshRemovedObservable = new BABYLON.Observable();
  15394. /**
  15395. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15396. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15397. * 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)
  15398. */
  15399. this.onRenderingGroupObservable = new BABYLON.Observable();
  15400. // Animations
  15401. this.animations = [];
  15402. /**
  15403. * 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).
  15404. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15405. */
  15406. this.onPrePointerObservable = new BABYLON.Observable();
  15407. /**
  15408. * Observable event triggered each time an input event is received from the rendering canvas
  15409. */
  15410. this.onPointerObservable = new BABYLON.Observable();
  15411. this._meshPickProceed = false;
  15412. this._previousHasSwiped = false;
  15413. this._currentPickResult = null;
  15414. this._previousPickResult = null;
  15415. this._isButtonPressed = false;
  15416. this._doubleClickOccured = false;
  15417. 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
  15418. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15419. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15420. this._startingPointerTime = 0;
  15421. this._previousStartingPointerTime = 0;
  15422. // Coordinate system
  15423. /**
  15424. * use right-handed coordinate system on this scene.
  15425. * @type {boolean}
  15426. */
  15427. this._useRightHandedSystem = false;
  15428. // Fog
  15429. /**
  15430. * is fog enabled on this scene.
  15431. * @type {boolean}
  15432. */
  15433. this._fogEnabled = true;
  15434. this._fogMode = Scene.FOGMODE_NONE;
  15435. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15436. this.fogDensity = 0.1;
  15437. this.fogStart = 0;
  15438. this.fogEnd = 1000.0;
  15439. // Lights
  15440. /**
  15441. * is shadow enabled on this scene.
  15442. * @type {boolean}
  15443. */
  15444. this._shadowsEnabled = true;
  15445. /**
  15446. * is light enabled on this scene.
  15447. * @type {boolean}
  15448. */
  15449. this._lightsEnabled = true;
  15450. /**
  15451. * All of the lights added to this scene.
  15452. * @see BABYLON.Light
  15453. * @type {BABYLON.Light[]}
  15454. */
  15455. this.lights = new Array();
  15456. // Cameras
  15457. /**
  15458. * All of the cameras added to this scene.
  15459. * @see BABYLON.Camera
  15460. * @type {BABYLON.Camera[]}
  15461. */
  15462. this.cameras = new Array();
  15463. this.activeCameras = new Array();
  15464. // Meshes
  15465. /**
  15466. * All of the (abstract) meshes added to this scene.
  15467. * @see BABYLON.AbstractMesh
  15468. * @type {BABYLON.AbstractMesh[]}
  15469. */
  15470. this.meshes = new Array();
  15471. // Geometries
  15472. this._geometries = new Array();
  15473. this.materials = new Array();
  15474. this.multiMaterials = new Array();
  15475. // Textures
  15476. this._texturesEnabled = true;
  15477. this.textures = new Array();
  15478. // Particles
  15479. this.particlesEnabled = true;
  15480. this.particleSystems = new Array();
  15481. // Sprites
  15482. this.spritesEnabled = true;
  15483. this.spriteManagers = new Array();
  15484. // Layers
  15485. this.layers = new Array();
  15486. this.highlightLayers = new Array();
  15487. // Skeletons
  15488. this._skeletonsEnabled = true;
  15489. this.skeletons = new Array();
  15490. // Morph targets
  15491. this.morphTargetManagers = new Array();
  15492. // Lens flares
  15493. this.lensFlaresEnabled = true;
  15494. this.lensFlareSystems = new Array();
  15495. // Collisions
  15496. this.collisionsEnabled = true;
  15497. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15498. // Postprocesses
  15499. this.postProcessesEnabled = true;
  15500. // Customs render targets
  15501. this.renderTargetsEnabled = true;
  15502. this.dumpNextRenderTargets = false;
  15503. this.customRenderTargets = new Array();
  15504. // Imported meshes
  15505. this.importedMeshesFiles = new Array();
  15506. // Probes
  15507. this.probesEnabled = true;
  15508. this.reflectionProbes = new Array();
  15509. this._actionManagers = new Array();
  15510. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15511. // Procedural textures
  15512. this.proceduralTexturesEnabled = true;
  15513. this._proceduralTextures = new Array();
  15514. this.soundTracks = new Array();
  15515. this._audioEnabled = true;
  15516. this._headphone = false;
  15517. // Performance counters
  15518. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15519. this._totalLightsCounter = new BABYLON.PerfCounter();
  15520. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15521. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15522. this._totalVertices = new BABYLON.PerfCounter();
  15523. this._activeIndices = new BABYLON.PerfCounter();
  15524. this._activeParticles = new BABYLON.PerfCounter();
  15525. this._lastFrameDuration = new BABYLON.PerfCounter();
  15526. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15527. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15528. this._particlesDuration = new BABYLON.PerfCounter();
  15529. this._renderDuration = new BABYLON.PerfCounter();
  15530. this._spritesDuration = new BABYLON.PerfCounter();
  15531. this._activeBones = new BABYLON.PerfCounter();
  15532. this._animationTime = 0;
  15533. this.animationTimeScale = 1;
  15534. this._renderId = 0;
  15535. this._executeWhenReadyTimeoutId = -1;
  15536. this._intermediateRendering = false;
  15537. this._viewUpdateFlag = -1;
  15538. this._projectionUpdateFlag = -1;
  15539. this._toBeDisposed = new BABYLON.SmartArray(256);
  15540. this._pendingData = []; //ANY
  15541. this._activeMeshes = new BABYLON.SmartArray(256);
  15542. this._processedMaterials = new BABYLON.SmartArray(256);
  15543. this._renderTargets = new BABYLON.SmartArray(256);
  15544. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15545. this._activeSkeletons = new BABYLON.SmartArray(32);
  15546. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15547. this._activeAnimatables = new Array();
  15548. this._transformMatrix = BABYLON.Matrix.Zero();
  15549. this.requireLightSorting = false;
  15550. this._uniqueIdCounter = 0;
  15551. this.offscreenRenderTarget = null;
  15552. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15553. this._engine.scenes.push(this);
  15554. this._uid = null;
  15555. this._renderingManager = new BABYLON.RenderingManager(this);
  15556. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15557. if (BABYLON.OutlineRenderer) {
  15558. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15559. }
  15560. this.attachControl();
  15561. if (BABYLON.SoundTrack) {
  15562. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15563. }
  15564. //simplification queue
  15565. if (BABYLON.SimplificationQueue) {
  15566. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15567. }
  15568. //collision coordinator initialization. For now legacy per default.
  15569. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15570. // Uniform Buffer
  15571. this._createUbo();
  15572. }
  15573. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15574. get: function () {
  15575. return Scene._FOGMODE_NONE;
  15576. },
  15577. enumerable: true,
  15578. configurable: true
  15579. });
  15580. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15581. get: function () {
  15582. return Scene._FOGMODE_EXP;
  15583. },
  15584. enumerable: true,
  15585. configurable: true
  15586. });
  15587. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15588. get: function () {
  15589. return Scene._FOGMODE_EXP2;
  15590. },
  15591. enumerable: true,
  15592. configurable: true
  15593. });
  15594. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15595. get: function () {
  15596. return Scene._FOGMODE_LINEAR;
  15597. },
  15598. enumerable: true,
  15599. configurable: true
  15600. });
  15601. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15602. /**
  15603. * Texture used in all pbr material as the reflection texture.
  15604. * As in the majority of the scene they are the same (exception for multi room and so on),
  15605. * this is easier to reference from here than from all the materials.
  15606. */
  15607. get: function () {
  15608. return this._environmentTexture;
  15609. },
  15610. /**
  15611. * Texture used in all pbr material as the reflection texture.
  15612. * As in the majority of the scene they are the same (exception for multi room and so on),
  15613. * this is easier to set here than in all the materials.
  15614. */
  15615. set: function (value) {
  15616. this._environmentTexture = value;
  15617. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15618. },
  15619. enumerable: true,
  15620. configurable: true
  15621. });
  15622. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15623. get: function () {
  15624. return this._forcePointsCloud;
  15625. },
  15626. set: function (value) {
  15627. if (this._forcePointsCloud === value) {
  15628. return;
  15629. }
  15630. this._forcePointsCloud = value;
  15631. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15632. },
  15633. enumerable: true,
  15634. configurable: true
  15635. });
  15636. Object.defineProperty(Scene.prototype, "onDispose", {
  15637. set: function (callback) {
  15638. if (this._onDisposeObserver) {
  15639. this.onDisposeObservable.remove(this._onDisposeObserver);
  15640. }
  15641. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15642. },
  15643. enumerable: true,
  15644. configurable: true
  15645. });
  15646. Object.defineProperty(Scene.prototype, "beforeRender", {
  15647. set: function (callback) {
  15648. if (this._onBeforeRenderObserver) {
  15649. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15650. }
  15651. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15652. },
  15653. enumerable: true,
  15654. configurable: true
  15655. });
  15656. Object.defineProperty(Scene.prototype, "afterRender", {
  15657. set: function (callback) {
  15658. if (this._onAfterRenderObserver) {
  15659. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15660. }
  15661. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15662. },
  15663. enumerable: true,
  15664. configurable: true
  15665. });
  15666. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15667. set: function (callback) {
  15668. if (this._onBeforeCameraRenderObserver) {
  15669. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15670. }
  15671. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15672. },
  15673. enumerable: true,
  15674. configurable: true
  15675. });
  15676. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15677. set: function (callback) {
  15678. if (this._onAfterCameraRenderObserver) {
  15679. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15680. }
  15681. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15682. },
  15683. enumerable: true,
  15684. configurable: true
  15685. });
  15686. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15687. get: function () {
  15688. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15689. },
  15690. enumerable: true,
  15691. configurable: true
  15692. });
  15693. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15694. get: function () {
  15695. return this._useRightHandedSystem;
  15696. },
  15697. set: function (value) {
  15698. if (this._useRightHandedSystem === value) {
  15699. return;
  15700. }
  15701. this._useRightHandedSystem = value;
  15702. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15703. },
  15704. enumerable: true,
  15705. configurable: true
  15706. });
  15707. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15708. get: function () {
  15709. return this._fogEnabled;
  15710. },
  15711. set: function (value) {
  15712. if (this._fogEnabled === value) {
  15713. return;
  15714. }
  15715. this._fogEnabled = value;
  15716. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15717. },
  15718. enumerable: true,
  15719. configurable: true
  15720. });
  15721. Object.defineProperty(Scene.prototype, "fogMode", {
  15722. get: function () {
  15723. return this._fogMode;
  15724. },
  15725. set: function (value) {
  15726. if (this._fogMode === value) {
  15727. return;
  15728. }
  15729. this._fogMode = value;
  15730. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15731. },
  15732. enumerable: true,
  15733. configurable: true
  15734. });
  15735. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15736. get: function () {
  15737. return this._shadowsEnabled;
  15738. },
  15739. set: function (value) {
  15740. if (this._shadowsEnabled === value) {
  15741. return;
  15742. }
  15743. this._shadowsEnabled = value;
  15744. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15745. },
  15746. enumerable: true,
  15747. configurable: true
  15748. });
  15749. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15750. get: function () {
  15751. return this._lightsEnabled;
  15752. },
  15753. set: function (value) {
  15754. if (this._lightsEnabled === value) {
  15755. return;
  15756. }
  15757. this._lightsEnabled = value;
  15758. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15759. },
  15760. enumerable: true,
  15761. configurable: true
  15762. });
  15763. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15764. get: function () {
  15765. if (!this._defaultMaterial) {
  15766. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15767. }
  15768. return this._defaultMaterial;
  15769. },
  15770. set: function (value) {
  15771. this._defaultMaterial = value;
  15772. },
  15773. enumerable: true,
  15774. configurable: true
  15775. });
  15776. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15777. get: function () {
  15778. return this._texturesEnabled;
  15779. },
  15780. set: function (value) {
  15781. if (this._texturesEnabled === value) {
  15782. return;
  15783. }
  15784. this._texturesEnabled = value;
  15785. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15786. },
  15787. enumerable: true,
  15788. configurable: true
  15789. });
  15790. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15791. get: function () {
  15792. return this._skeletonsEnabled;
  15793. },
  15794. set: function (value) {
  15795. if (this._skeletonsEnabled === value) {
  15796. return;
  15797. }
  15798. this._skeletonsEnabled = value;
  15799. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15800. },
  15801. enumerable: true,
  15802. configurable: true
  15803. });
  15804. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15805. get: function () {
  15806. if (!this._postProcessRenderPipelineManager) {
  15807. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15808. }
  15809. return this._postProcessRenderPipelineManager;
  15810. },
  15811. enumerable: true,
  15812. configurable: true
  15813. });
  15814. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15815. get: function () {
  15816. return this._frustumPlanes;
  15817. },
  15818. enumerable: true,
  15819. configurable: true
  15820. });
  15821. Object.defineProperty(Scene.prototype, "debugLayer", {
  15822. // Properties
  15823. get: function () {
  15824. if (!this._debugLayer) {
  15825. this._debugLayer = new BABYLON.DebugLayer(this);
  15826. }
  15827. return this._debugLayer;
  15828. },
  15829. enumerable: true,
  15830. configurable: true
  15831. });
  15832. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15833. get: function () {
  15834. return this._workerCollisions;
  15835. },
  15836. set: function (enabled) {
  15837. if (!BABYLON.CollisionCoordinatorLegacy) {
  15838. return;
  15839. }
  15840. enabled = (enabled && !!Worker);
  15841. this._workerCollisions = enabled;
  15842. if (this.collisionCoordinator) {
  15843. this.collisionCoordinator.destroy();
  15844. }
  15845. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15846. this.collisionCoordinator.init(this);
  15847. },
  15848. enumerable: true,
  15849. configurable: true
  15850. });
  15851. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15852. get: function () {
  15853. return this._selectionOctree;
  15854. },
  15855. enumerable: true,
  15856. configurable: true
  15857. });
  15858. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15859. /**
  15860. * The mesh that is currently under the pointer.
  15861. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15862. */
  15863. get: function () {
  15864. return this._pointerOverMesh;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. Object.defineProperty(Scene.prototype, "pointerX", {
  15870. /**
  15871. * Current on-screen X position of the pointer
  15872. * @return {number} X position of the pointer
  15873. */
  15874. get: function () {
  15875. return this._pointerX;
  15876. },
  15877. enumerable: true,
  15878. configurable: true
  15879. });
  15880. Object.defineProperty(Scene.prototype, "pointerY", {
  15881. /**
  15882. * Current on-screen Y position of the pointer
  15883. * @return {number} Y position of the pointer
  15884. */
  15885. get: function () {
  15886. return this._pointerY;
  15887. },
  15888. enumerable: true,
  15889. configurable: true
  15890. });
  15891. Scene.prototype.getCachedMaterial = function () {
  15892. return this._cachedMaterial;
  15893. };
  15894. Scene.prototype.getCachedEffect = function () {
  15895. return this._cachedEffect;
  15896. };
  15897. Scene.prototype.getCachedVisibility = function () {
  15898. return this._cachedVisibility;
  15899. };
  15900. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15901. if (visibility === void 0) { visibility = 0; }
  15902. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15903. };
  15904. Scene.prototype.getBoundingBoxRenderer = function () {
  15905. if (!this._boundingBoxRenderer) {
  15906. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15907. }
  15908. return this._boundingBoxRenderer;
  15909. };
  15910. Scene.prototype.getOutlineRenderer = function () {
  15911. return this._outlineRenderer;
  15912. };
  15913. Scene.prototype.getEngine = function () {
  15914. return this._engine;
  15915. };
  15916. Scene.prototype.getTotalVertices = function () {
  15917. return this._totalVertices.current;
  15918. };
  15919. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15920. get: function () {
  15921. return this._totalVertices;
  15922. },
  15923. enumerable: true,
  15924. configurable: true
  15925. });
  15926. Scene.prototype.getActiveIndices = function () {
  15927. return this._activeIndices.current;
  15928. };
  15929. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15930. get: function () {
  15931. return this._activeIndices;
  15932. },
  15933. enumerable: true,
  15934. configurable: true
  15935. });
  15936. Scene.prototype.getActiveParticles = function () {
  15937. return this._activeParticles.current;
  15938. };
  15939. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15940. get: function () {
  15941. return this._activeParticles;
  15942. },
  15943. enumerable: true,
  15944. configurable: true
  15945. });
  15946. Scene.prototype.getActiveBones = function () {
  15947. return this._activeBones.current;
  15948. };
  15949. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15950. get: function () {
  15951. return this._activeBones;
  15952. },
  15953. enumerable: true,
  15954. configurable: true
  15955. });
  15956. // Stats
  15957. Scene.prototype.getLastFrameDuration = function () {
  15958. return this._lastFrameDuration.current;
  15959. };
  15960. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15961. get: function () {
  15962. return this._lastFrameDuration;
  15963. },
  15964. enumerable: true,
  15965. configurable: true
  15966. });
  15967. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15968. return this._evaluateActiveMeshesDuration.current;
  15969. };
  15970. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15971. get: function () {
  15972. return this._evaluateActiveMeshesDuration;
  15973. },
  15974. enumerable: true,
  15975. configurable: true
  15976. });
  15977. Scene.prototype.getActiveMeshes = function () {
  15978. return this._activeMeshes;
  15979. };
  15980. Scene.prototype.getRenderTargetsDuration = function () {
  15981. return this._renderTargetsDuration.current;
  15982. };
  15983. Scene.prototype.getRenderDuration = function () {
  15984. return this._renderDuration.current;
  15985. };
  15986. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15987. get: function () {
  15988. return this._renderDuration;
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Scene.prototype.getParticlesDuration = function () {
  15994. return this._particlesDuration.current;
  15995. };
  15996. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15997. get: function () {
  15998. return this._particlesDuration;
  15999. },
  16000. enumerable: true,
  16001. configurable: true
  16002. });
  16003. Scene.prototype.getSpritesDuration = function () {
  16004. return this._spritesDuration.current;
  16005. };
  16006. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16007. get: function () {
  16008. return this._spritesDuration;
  16009. },
  16010. enumerable: true,
  16011. configurable: true
  16012. });
  16013. Scene.prototype.getAnimationRatio = function () {
  16014. return this._animationRatio;
  16015. };
  16016. Scene.prototype.getRenderId = function () {
  16017. return this._renderId;
  16018. };
  16019. Scene.prototype.incrementRenderId = function () {
  16020. this._renderId++;
  16021. };
  16022. Scene.prototype._updatePointerPosition = function (evt) {
  16023. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16024. this._pointerX = evt.clientX - canvasRect.left;
  16025. this._pointerY = evt.clientY - canvasRect.top;
  16026. this._unTranslatedPointerX = this._pointerX;
  16027. this._unTranslatedPointerY = this._pointerY;
  16028. if (this.cameraToUseForPointers) {
  16029. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16030. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16031. }
  16032. };
  16033. Scene.prototype._createUbo = function () {
  16034. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16035. this._sceneUbo.addUniform("viewProjection", 16);
  16036. this._sceneUbo.addUniform("view", 16);
  16037. };
  16038. // Pointers handling
  16039. /**
  16040. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16041. * @param attachUp defines if you want to attach events to pointerup
  16042. * @param attachDown defines if you want to attach events to pointerdown
  16043. * @param attachMove defines if you want to attach events to pointermove
  16044. */
  16045. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16046. var _this = this;
  16047. if (attachUp === void 0) { attachUp = true; }
  16048. if (attachDown === void 0) { attachDown = true; }
  16049. if (attachMove === void 0) { attachMove = true; }
  16050. this._initActionManager = function (act, clickInfo) {
  16051. if (!_this._meshPickProceed) {
  16052. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16053. _this._currentPickResult = pickResult;
  16054. if (pickResult) {
  16055. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16056. }
  16057. _this._meshPickProceed = true;
  16058. }
  16059. return act;
  16060. };
  16061. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16062. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16063. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16064. btn !== _this._previousButtonPressed) {
  16065. _this._doubleClickOccured = false;
  16066. clickInfo.singleClick = true;
  16067. clickInfo.ignore = false;
  16068. cb(clickInfo, _this._currentPickResult);
  16069. }
  16070. };
  16071. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16072. var clickInfo = new ClickInfo();
  16073. _this._currentPickResult = null;
  16074. var act;
  16075. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16076. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16077. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16078. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16079. act = _this._initActionManager(act, clickInfo);
  16080. if (act)
  16081. checkPicking = act.hasPickTriggers;
  16082. }
  16083. if (checkPicking) {
  16084. var btn = evt.button;
  16085. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16086. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16087. if (!clickInfo.hasSwiped) {
  16088. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16089. if (!checkSingleClickImmediately) {
  16090. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16091. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16092. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16093. act = _this._initActionManager(act, clickInfo);
  16094. if (act)
  16095. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16096. }
  16097. }
  16098. if (checkSingleClickImmediately) {
  16099. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16100. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16101. btn !== _this._previousButtonPressed) {
  16102. clickInfo.singleClick = true;
  16103. cb(clickInfo, _this._currentPickResult);
  16104. }
  16105. }
  16106. else {
  16107. // wait that no double click has been raised during the double click delay
  16108. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16109. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16110. }
  16111. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16112. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16113. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16114. act = _this._initActionManager(act, clickInfo);
  16115. if (act)
  16116. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16117. }
  16118. if (checkDoubleClick) {
  16119. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16120. if (btn === _this._previousButtonPressed &&
  16121. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16122. !_this._doubleClickOccured) {
  16123. // pointer has not moved for 2 clicks, it's a double click
  16124. if (!clickInfo.hasSwiped &&
  16125. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16126. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16127. _this._previousStartingPointerTime = 0;
  16128. _this._doubleClickOccured = true;
  16129. clickInfo.doubleClick = true;
  16130. clickInfo.ignore = false;
  16131. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16132. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16133. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16134. cb(clickInfo, _this._currentPickResult);
  16135. }
  16136. else {
  16137. _this._doubleClickOccured = false;
  16138. _this._previousStartingPointerTime = _this._startingPointerTime;
  16139. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16140. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16141. _this._previousButtonPressed = btn;
  16142. _this._previousHasSwiped = clickInfo.hasSwiped;
  16143. if (Scene.ExclusiveDoubleClickMode) {
  16144. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16145. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16146. }
  16147. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16148. cb(clickInfo, _this._previousPickResult);
  16149. }
  16150. else {
  16151. cb(clickInfo, _this._currentPickResult);
  16152. }
  16153. }
  16154. }
  16155. else {
  16156. _this._doubleClickOccured = false;
  16157. _this._previousStartingPointerTime = _this._startingPointerTime;
  16158. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16159. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16160. _this._previousButtonPressed = btn;
  16161. _this._previousHasSwiped = clickInfo.hasSwiped;
  16162. }
  16163. }
  16164. }
  16165. }
  16166. clickInfo.ignore = true;
  16167. cb(clickInfo, _this._currentPickResult);
  16168. };
  16169. var spritePredicate = function (sprite) {
  16170. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16171. };
  16172. this._onPointerMove = function (evt) {
  16173. _this._updatePointerPosition(evt);
  16174. // PreObservable support
  16175. if (_this.onPrePointerObservable.hasObservers()) {
  16176. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16177. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16178. _this.onPrePointerObservable.notifyObservers(pi, type);
  16179. if (pi.skipOnPointerObservable) {
  16180. return;
  16181. }
  16182. }
  16183. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16184. return;
  16185. }
  16186. var canvas = _this._engine.getRenderingCanvas();
  16187. if (!_this.pointerMovePredicate) {
  16188. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16189. }
  16190. // Meshes
  16191. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16192. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16193. _this.setPointerOverSprite(null);
  16194. _this.setPointerOverMesh(pickResult.pickedMesh);
  16195. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16196. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16197. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16198. }
  16199. else {
  16200. canvas.style.cursor = _this.hoverCursor;
  16201. }
  16202. }
  16203. else {
  16204. canvas.style.cursor = "";
  16205. }
  16206. }
  16207. else {
  16208. _this.setPointerOverMesh(null);
  16209. // Sprites
  16210. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16211. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16212. _this.setPointerOverSprite(pickResult.pickedSprite);
  16213. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16214. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16215. }
  16216. else {
  16217. canvas.style.cursor = _this.hoverCursor;
  16218. }
  16219. }
  16220. else {
  16221. _this.setPointerOverSprite(null);
  16222. // Restore pointer
  16223. canvas.style.cursor = "";
  16224. }
  16225. }
  16226. if (_this.onPointerMove) {
  16227. _this.onPointerMove(evt, pickResult);
  16228. }
  16229. if (_this.onPointerObservable.hasObservers()) {
  16230. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16231. var pi = new PointerInfo(type, evt, pickResult);
  16232. _this.onPointerObservable.notifyObservers(pi, type);
  16233. }
  16234. };
  16235. this._onPointerDown = function (evt) {
  16236. _this._isButtonPressed = true;
  16237. _this._pickedDownMesh = null;
  16238. _this._meshPickProceed = false;
  16239. _this._updatePointerPosition(evt);
  16240. // PreObservable support
  16241. if (_this.onPrePointerObservable.hasObservers()) {
  16242. var type = PointerEventTypes.POINTERDOWN;
  16243. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16244. _this.onPrePointerObservable.notifyObservers(pi, type);
  16245. if (pi.skipOnPointerObservable) {
  16246. return;
  16247. }
  16248. }
  16249. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16250. return;
  16251. }
  16252. _this._startingPointerPosition.x = _this._pointerX;
  16253. _this._startingPointerPosition.y = _this._pointerY;
  16254. _this._startingPointerTime = new Date().getTime();
  16255. if (!_this.pointerDownPredicate) {
  16256. _this.pointerDownPredicate = function (mesh) {
  16257. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16258. };
  16259. }
  16260. // Meshes
  16261. _this._pickedDownMesh = null;
  16262. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16263. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16264. _this._pickedDownMesh = pickResult.pickedMesh;
  16265. var actionManager = pickResult.pickedMesh.actionManager;
  16266. if (actionManager) {
  16267. if (actionManager.hasPickTriggers) {
  16268. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16269. switch (evt.button) {
  16270. case 0:
  16271. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16272. break;
  16273. case 1:
  16274. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16275. break;
  16276. case 2:
  16277. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16278. break;
  16279. }
  16280. }
  16281. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16282. window.setTimeout((function () {
  16283. var _this = this;
  16284. 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);
  16285. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16286. if (this._isButtonPressed &&
  16287. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16288. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16289. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16290. this._startingPointerTime = 0;
  16291. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16292. }
  16293. }
  16294. }).bind(_this), Scene.LongPressDelay);
  16295. }
  16296. }
  16297. }
  16298. if (_this.onPointerDown) {
  16299. _this.onPointerDown(evt, pickResult);
  16300. }
  16301. if (_this.onPointerObservable.hasObservers()) {
  16302. var type = PointerEventTypes.POINTERDOWN;
  16303. var pi = new PointerInfo(type, evt, pickResult);
  16304. _this.onPointerObservable.notifyObservers(pi, type);
  16305. }
  16306. // Sprites
  16307. _this._pickedDownSprite = null;
  16308. if (_this.spriteManagers.length > 0) {
  16309. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16310. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16311. if (pickResult.pickedSprite.actionManager) {
  16312. _this._pickedDownSprite = pickResult.pickedSprite;
  16313. switch (evt.button) {
  16314. case 0:
  16315. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16316. break;
  16317. case 1:
  16318. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16319. break;
  16320. case 2:
  16321. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16322. break;
  16323. }
  16324. if (pickResult.pickedSprite.actionManager) {
  16325. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16326. }
  16327. }
  16328. }
  16329. }
  16330. };
  16331. this._onPointerUp = function (evt) {
  16332. _this._isButtonPressed = false;
  16333. _this._pickedUpMesh = null;
  16334. _this._meshPickProceed = false;
  16335. _this._updatePointerPosition(evt);
  16336. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16337. // PreObservable support
  16338. if (this.onPrePointerObservable.hasObservers()) {
  16339. if (!clickInfo.ignore) {
  16340. if (!clickInfo.hasSwiped) {
  16341. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16342. var type = PointerEventTypes.POINTERTAP;
  16343. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16344. this.onPrePointerObservable.notifyObservers(pi, type);
  16345. if (pi.skipOnPointerObservable) {
  16346. return;
  16347. }
  16348. }
  16349. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16350. var type = PointerEventTypes.POINTERDOUBLETAP;
  16351. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16352. this.onPrePointerObservable.notifyObservers(pi, type);
  16353. if (pi.skipOnPointerObservable) {
  16354. return;
  16355. }
  16356. }
  16357. }
  16358. }
  16359. else {
  16360. var type = PointerEventTypes.POINTERUP;
  16361. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16362. this.onPrePointerObservable.notifyObservers(pi, type);
  16363. if (pi.skipOnPointerObservable) {
  16364. return;
  16365. }
  16366. }
  16367. }
  16368. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16369. return;
  16370. }
  16371. if (!this.pointerUpPredicate) {
  16372. this.pointerUpPredicate = function (mesh) {
  16373. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16374. };
  16375. }
  16376. // Meshes
  16377. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16378. this._initActionManager(null, clickInfo);
  16379. }
  16380. if (!pickResult) {
  16381. pickResult = this._currentPickResult;
  16382. }
  16383. if (pickResult && pickResult && pickResult.pickedMesh) {
  16384. this._pickedUpMesh = pickResult.pickedMesh;
  16385. if (this._pickedDownMesh === this._pickedUpMesh) {
  16386. if (this.onPointerPick) {
  16387. this.onPointerPick(evt, pickResult);
  16388. }
  16389. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16390. var type = PointerEventTypes.POINTERPICK;
  16391. var pi = new PointerInfo(type, evt, pickResult);
  16392. this.onPointerObservable.notifyObservers(pi, type);
  16393. }
  16394. }
  16395. if (pickResult.pickedMesh.actionManager) {
  16396. if (clickInfo.ignore) {
  16397. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16398. }
  16399. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16400. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16401. }
  16402. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16403. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16404. }
  16405. }
  16406. }
  16407. if (this._pickedDownMesh &&
  16408. this._pickedDownMesh.actionManager &&
  16409. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16410. this._pickedDownMesh !== this._pickedUpMesh) {
  16411. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16412. }
  16413. if (this.onPointerUp) {
  16414. this.onPointerUp(evt, pickResult);
  16415. }
  16416. if (this.onPointerObservable.hasObservers()) {
  16417. if (!clickInfo.ignore) {
  16418. if (!clickInfo.hasSwiped) {
  16419. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16420. var type = PointerEventTypes.POINTERTAP;
  16421. var pi = new PointerInfo(type, evt, pickResult);
  16422. this.onPointerObservable.notifyObservers(pi, type);
  16423. }
  16424. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16425. var type = PointerEventTypes.POINTERDOUBLETAP;
  16426. var pi = new PointerInfo(type, evt, pickResult);
  16427. this.onPointerObservable.notifyObservers(pi, type);
  16428. }
  16429. }
  16430. }
  16431. else {
  16432. var type = PointerEventTypes.POINTERUP;
  16433. var pi = new PointerInfo(type, evt, pickResult);
  16434. this.onPointerObservable.notifyObservers(pi, type);
  16435. }
  16436. }
  16437. // Sprites
  16438. if (this.spriteManagers.length > 0) {
  16439. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16440. if (pickResult.hit && pickResult.pickedSprite) {
  16441. if (pickResult.pickedSprite.actionManager) {
  16442. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16443. if (pickResult.pickedSprite.actionManager) {
  16444. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16445. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16446. }
  16447. }
  16448. }
  16449. }
  16450. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16451. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16452. }
  16453. }
  16454. this._previousPickResult = this._currentPickResult;
  16455. }).bind(_this));
  16456. };
  16457. this._onKeyDown = function (evt) {
  16458. if (_this.actionManager) {
  16459. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16460. }
  16461. };
  16462. this._onKeyUp = function (evt) {
  16463. if (_this.actionManager) {
  16464. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16465. }
  16466. };
  16467. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16468. var canvas = this._engine.getRenderingCanvas();
  16469. if (attachMove) {
  16470. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16471. // Wheel
  16472. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16473. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16474. }
  16475. if (attachDown) {
  16476. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16477. }
  16478. if (attachUp) {
  16479. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16480. }
  16481. canvas.tabIndex = 1;
  16482. canvas.addEventListener("keydown", this._onKeyDown, false);
  16483. canvas.addEventListener("keyup", this._onKeyUp, false);
  16484. };
  16485. Scene.prototype.detachControl = function () {
  16486. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16487. var canvas = this._engine.getRenderingCanvas();
  16488. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16489. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16490. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16491. // Wheel
  16492. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16493. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16494. canvas.removeEventListener("keydown", this._onKeyDown);
  16495. canvas.removeEventListener("keyup", this._onKeyUp);
  16496. };
  16497. // Ready
  16498. Scene.prototype.isReady = function () {
  16499. if (this._pendingData.length > 0) {
  16500. return false;
  16501. }
  16502. var index;
  16503. // Geometries
  16504. for (index = 0; index < this._geometries.length; index++) {
  16505. var geometry = this._geometries[index];
  16506. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16507. return false;
  16508. }
  16509. }
  16510. // Meshes
  16511. for (index = 0; index < this.meshes.length; index++) {
  16512. var mesh = this.meshes[index];
  16513. if (!mesh.isEnabled()) {
  16514. continue;
  16515. }
  16516. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16517. continue;
  16518. }
  16519. if (!mesh.isReady()) {
  16520. return false;
  16521. }
  16522. var mat = mesh.material;
  16523. if (mat) {
  16524. if (!mat.isReady(mesh)) {
  16525. return false;
  16526. }
  16527. }
  16528. }
  16529. return true;
  16530. };
  16531. Scene.prototype.resetCachedMaterial = function () {
  16532. this._cachedMaterial = null;
  16533. this._cachedEffect = null;
  16534. this._cachedVisibility = null;
  16535. };
  16536. Scene.prototype.registerBeforeRender = function (func) {
  16537. this.onBeforeRenderObservable.add(func);
  16538. };
  16539. Scene.prototype.unregisterBeforeRender = function (func) {
  16540. this.onBeforeRenderObservable.removeCallback(func);
  16541. };
  16542. Scene.prototype.registerAfterRender = function (func) {
  16543. this.onAfterRenderObservable.add(func);
  16544. };
  16545. Scene.prototype.unregisterAfterRender = function (func) {
  16546. this.onAfterRenderObservable.removeCallback(func);
  16547. };
  16548. Scene.prototype._addPendingData = function (data) {
  16549. this._pendingData.push(data);
  16550. };
  16551. Scene.prototype._removePendingData = function (data) {
  16552. var index = this._pendingData.indexOf(data);
  16553. if (index !== -1) {
  16554. this._pendingData.splice(index, 1);
  16555. }
  16556. };
  16557. Scene.prototype.getWaitingItemsCount = function () {
  16558. return this._pendingData.length;
  16559. };
  16560. /**
  16561. * Registers a function to be executed when the scene is ready.
  16562. * @param {Function} func - the function to be executed.
  16563. */
  16564. Scene.prototype.executeWhenReady = function (func) {
  16565. var _this = this;
  16566. this.onReadyObservable.add(func);
  16567. if (this._executeWhenReadyTimeoutId !== -1) {
  16568. return;
  16569. }
  16570. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16571. _this._checkIsReady();
  16572. }, 150);
  16573. };
  16574. Scene.prototype._checkIsReady = function () {
  16575. var _this = this;
  16576. if (this.isReady()) {
  16577. this.onReadyObservable.notifyObservers(this);
  16578. this.onReadyObservable.clear();
  16579. this._executeWhenReadyTimeoutId = -1;
  16580. return;
  16581. }
  16582. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16583. _this._checkIsReady();
  16584. }, 150);
  16585. };
  16586. // Animations
  16587. /**
  16588. * Will start the animation sequence of a given target
  16589. * @param target - the target
  16590. * @param {number} from - from which frame should animation start
  16591. * @param {number} to - till which frame should animation run.
  16592. * @param {boolean} [loop] - should the animation loop
  16593. * @param {number} [speedRatio] - the speed in which to run the animation
  16594. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16595. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16596. * @return {BABYLON.Animatable} the animatable object created for this animation
  16597. * @see BABYLON.Animatable
  16598. * @see http://doc.babylonjs.com/page.php?p=22081
  16599. */
  16600. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16601. if (speedRatio === void 0) { speedRatio = 1.0; }
  16602. if (from > to && speedRatio > 0) {
  16603. speedRatio *= -1;
  16604. }
  16605. this.stopAnimation(target);
  16606. if (!animatable) {
  16607. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16608. }
  16609. // Local animations
  16610. if (target.animations) {
  16611. animatable.appendAnimations(target, target.animations);
  16612. }
  16613. // Children animations
  16614. if (target.getAnimatables) {
  16615. var animatables = target.getAnimatables();
  16616. for (var index = 0; index < animatables.length; index++) {
  16617. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16618. }
  16619. }
  16620. animatable.reset();
  16621. return animatable;
  16622. };
  16623. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16624. if (speedRatio === undefined) {
  16625. speedRatio = 1.0;
  16626. }
  16627. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16628. return animatable;
  16629. };
  16630. Scene.prototype.getAnimatableByTarget = function (target) {
  16631. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16632. if (this._activeAnimatables[index].target === target) {
  16633. return this._activeAnimatables[index];
  16634. }
  16635. }
  16636. return null;
  16637. };
  16638. Object.defineProperty(Scene.prototype, "Animatables", {
  16639. get: function () {
  16640. return this._activeAnimatables;
  16641. },
  16642. enumerable: true,
  16643. configurable: true
  16644. });
  16645. /**
  16646. * Will stop the animation of the given target
  16647. * @param target - the target
  16648. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16649. * @see beginAnimation
  16650. */
  16651. Scene.prototype.stopAnimation = function (target, animationName) {
  16652. var animatable = this.getAnimatableByTarget(target);
  16653. if (animatable) {
  16654. animatable.stop(animationName);
  16655. }
  16656. };
  16657. Scene.prototype._animate = function () {
  16658. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16659. return;
  16660. }
  16661. // Getting time
  16662. var now = BABYLON.Tools.Now;
  16663. if (!this._animationTimeLast) {
  16664. if (this._pendingData.length > 0) {
  16665. return;
  16666. }
  16667. this._animationTimeLast = now;
  16668. }
  16669. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16670. this._animationTime += deltaTime;
  16671. this._animationTimeLast = now;
  16672. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16673. this._activeAnimatables[index]._animate(this._animationTime);
  16674. }
  16675. };
  16676. // Matrix
  16677. Scene.prototype.getViewMatrix = function () {
  16678. return this._viewMatrix;
  16679. };
  16680. Scene.prototype.getProjectionMatrix = function () {
  16681. return this._projectionMatrix;
  16682. };
  16683. Scene.prototype.getTransformMatrix = function () {
  16684. return this._transformMatrix;
  16685. };
  16686. Scene.prototype.setTransformMatrix = function (view, projection) {
  16687. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16688. return;
  16689. }
  16690. this._viewUpdateFlag = view.updateFlag;
  16691. this._projectionUpdateFlag = projection.updateFlag;
  16692. this._viewMatrix = view;
  16693. this._projectionMatrix = projection;
  16694. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16695. // Update frustum
  16696. if (!this._frustumPlanes) {
  16697. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16698. }
  16699. else {
  16700. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16701. }
  16702. if (this._sceneUbo.useUbo) {
  16703. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16704. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16705. this._sceneUbo.update();
  16706. }
  16707. };
  16708. Scene.prototype.getSceneUniformBuffer = function () {
  16709. return this._sceneUbo;
  16710. };
  16711. // Methods
  16712. Scene.prototype.getUniqueId = function () {
  16713. var result = this._uniqueIdCounter;
  16714. this._uniqueIdCounter++;
  16715. return result;
  16716. };
  16717. Scene.prototype.addMesh = function (newMesh) {
  16718. newMesh.uniqueId = this.getUniqueId();
  16719. var position = this.meshes.push(newMesh);
  16720. //notify the collision coordinator
  16721. if (this.collisionCoordinator) {
  16722. this.collisionCoordinator.onMeshAdded(newMesh);
  16723. }
  16724. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16725. };
  16726. Scene.prototype.removeMesh = function (toRemove) {
  16727. var index = this.meshes.indexOf(toRemove);
  16728. if (index !== -1) {
  16729. // Remove from the scene if mesh found
  16730. this.meshes.splice(index, 1);
  16731. }
  16732. //notify the collision coordinator
  16733. if (this.collisionCoordinator) {
  16734. this.collisionCoordinator.onMeshRemoved(toRemove);
  16735. }
  16736. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16737. return index;
  16738. };
  16739. Scene.prototype.removeSkeleton = function (toRemove) {
  16740. var index = this.skeletons.indexOf(toRemove);
  16741. if (index !== -1) {
  16742. // Remove from the scene if found
  16743. this.skeletons.splice(index, 1);
  16744. }
  16745. return index;
  16746. };
  16747. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16748. var index = this.morphTargetManagers.indexOf(toRemove);
  16749. if (index !== -1) {
  16750. // Remove from the scene if found
  16751. this.morphTargetManagers.splice(index, 1);
  16752. }
  16753. return index;
  16754. };
  16755. Scene.prototype.removeLight = function (toRemove) {
  16756. var index = this.lights.indexOf(toRemove);
  16757. if (index !== -1) {
  16758. // Remove from the scene if mesh found
  16759. this.lights.splice(index, 1);
  16760. this.sortLightsByPriority();
  16761. }
  16762. this.onLightRemovedObservable.notifyObservers(toRemove);
  16763. return index;
  16764. };
  16765. Scene.prototype.removeCamera = function (toRemove) {
  16766. var index = this.cameras.indexOf(toRemove);
  16767. if (index !== -1) {
  16768. // Remove from the scene if mesh found
  16769. this.cameras.splice(index, 1);
  16770. }
  16771. // Remove from activeCameras
  16772. var index2 = this.activeCameras.indexOf(toRemove);
  16773. if (index2 !== -1) {
  16774. // Remove from the scene if mesh found
  16775. this.activeCameras.splice(index2, 1);
  16776. }
  16777. // Reset the activeCamera
  16778. if (this.activeCamera === toRemove) {
  16779. if (this.cameras.length > 0) {
  16780. this.activeCamera = this.cameras[0];
  16781. }
  16782. else {
  16783. this.activeCamera = null;
  16784. }
  16785. }
  16786. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16787. return index;
  16788. };
  16789. Scene.prototype.addLight = function (newLight) {
  16790. newLight.uniqueId = this.getUniqueId();
  16791. this.lights.push(newLight);
  16792. this.sortLightsByPriority();
  16793. this.onNewLightAddedObservable.notifyObservers(newLight);
  16794. };
  16795. Scene.prototype.sortLightsByPriority = function () {
  16796. if (this.requireLightSorting) {
  16797. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16798. }
  16799. };
  16800. Scene.prototype.addCamera = function (newCamera) {
  16801. newCamera.uniqueId = this.getUniqueId();
  16802. var position = this.cameras.push(newCamera);
  16803. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16804. };
  16805. /**
  16806. * Switch active camera
  16807. * @param {Camera} newCamera - new active camera
  16808. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16809. */
  16810. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16811. if (attachControl === void 0) { attachControl = true; }
  16812. var canvas = this._engine.getRenderingCanvas();
  16813. this.activeCamera.detachControl(canvas);
  16814. this.activeCamera = newCamera;
  16815. if (attachControl) {
  16816. newCamera.attachControl(canvas);
  16817. }
  16818. };
  16819. /**
  16820. * sets the active camera of the scene using its ID
  16821. * @param {string} id - the camera's ID
  16822. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16823. * @see activeCamera
  16824. */
  16825. Scene.prototype.setActiveCameraByID = function (id) {
  16826. var camera = this.getCameraByID(id);
  16827. if (camera) {
  16828. this.activeCamera = camera;
  16829. return camera;
  16830. }
  16831. return null;
  16832. };
  16833. /**
  16834. * sets the active camera of the scene using its name
  16835. * @param {string} name - the camera's name
  16836. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16837. * @see activeCamera
  16838. */
  16839. Scene.prototype.setActiveCameraByName = function (name) {
  16840. var camera = this.getCameraByName(name);
  16841. if (camera) {
  16842. this.activeCamera = camera;
  16843. return camera;
  16844. }
  16845. return null;
  16846. };
  16847. /**
  16848. * get a material using its id
  16849. * @param {string} the material's ID
  16850. * @return {BABYLON.Material|null} the material or null if none found.
  16851. */
  16852. Scene.prototype.getMaterialByID = function (id) {
  16853. for (var index = 0; index < this.materials.length; index++) {
  16854. if (this.materials[index].id === id) {
  16855. return this.materials[index];
  16856. }
  16857. }
  16858. return null;
  16859. };
  16860. /**
  16861. * get a material using its name
  16862. * @param {string} the material's name
  16863. * @return {BABYLON.Material|null} the material or null if none found.
  16864. */
  16865. Scene.prototype.getMaterialByName = function (name) {
  16866. for (var index = 0; index < this.materials.length; index++) {
  16867. if (this.materials[index].name === name) {
  16868. return this.materials[index];
  16869. }
  16870. }
  16871. return null;
  16872. };
  16873. Scene.prototype.getLensFlareSystemByName = function (name) {
  16874. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16875. if (this.lensFlareSystems[index].name === name) {
  16876. return this.lensFlareSystems[index];
  16877. }
  16878. }
  16879. return null;
  16880. };
  16881. Scene.prototype.getLensFlareSystemByID = function (id) {
  16882. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16883. if (this.lensFlareSystems[index].id === id) {
  16884. return this.lensFlareSystems[index];
  16885. }
  16886. }
  16887. return null;
  16888. };
  16889. Scene.prototype.getCameraByID = function (id) {
  16890. for (var index = 0; index < this.cameras.length; index++) {
  16891. if (this.cameras[index].id === id) {
  16892. return this.cameras[index];
  16893. }
  16894. }
  16895. return null;
  16896. };
  16897. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16898. for (var index = 0; index < this.cameras.length; index++) {
  16899. if (this.cameras[index].uniqueId === uniqueId) {
  16900. return this.cameras[index];
  16901. }
  16902. }
  16903. return null;
  16904. };
  16905. /**
  16906. * get a camera using its name
  16907. * @param {string} the camera's name
  16908. * @return {BABYLON.Camera|null} the camera or null if none found.
  16909. */
  16910. Scene.prototype.getCameraByName = function (name) {
  16911. for (var index = 0; index < this.cameras.length; index++) {
  16912. if (this.cameras[index].name === name) {
  16913. return this.cameras[index];
  16914. }
  16915. }
  16916. return null;
  16917. };
  16918. /**
  16919. * get a bone using its id
  16920. * @param {string} the bone's id
  16921. * @return {BABYLON.Bone|null} the bone or null if not found
  16922. */
  16923. Scene.prototype.getBoneByID = function (id) {
  16924. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16925. var skeleton = this.skeletons[skeletonIndex];
  16926. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16927. if (skeleton.bones[boneIndex].id === id) {
  16928. return skeleton.bones[boneIndex];
  16929. }
  16930. }
  16931. }
  16932. return null;
  16933. };
  16934. /**
  16935. * get a bone using its id
  16936. * @param {string} the bone's name
  16937. * @return {BABYLON.Bone|null} the bone or null if not found
  16938. */
  16939. Scene.prototype.getBoneByName = function (name) {
  16940. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16941. var skeleton = this.skeletons[skeletonIndex];
  16942. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16943. if (skeleton.bones[boneIndex].name === name) {
  16944. return skeleton.bones[boneIndex];
  16945. }
  16946. }
  16947. }
  16948. return null;
  16949. };
  16950. /**
  16951. * get a light node using its name
  16952. * @param {string} the light's name
  16953. * @return {BABYLON.Light|null} the light or null if none found.
  16954. */
  16955. Scene.prototype.getLightByName = function (name) {
  16956. for (var index = 0; index < this.lights.length; index++) {
  16957. if (this.lights[index].name === name) {
  16958. return this.lights[index];
  16959. }
  16960. }
  16961. return null;
  16962. };
  16963. /**
  16964. * get a light node using its ID
  16965. * @param {string} the light's id
  16966. * @return {BABYLON.Light|null} the light or null if none found.
  16967. */
  16968. Scene.prototype.getLightByID = function (id) {
  16969. for (var index = 0; index < this.lights.length; index++) {
  16970. if (this.lights[index].id === id) {
  16971. return this.lights[index];
  16972. }
  16973. }
  16974. return null;
  16975. };
  16976. /**
  16977. * get a light node using its scene-generated unique ID
  16978. * @param {number} the light's unique id
  16979. * @return {BABYLON.Light|null} the light or null if none found.
  16980. */
  16981. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16982. for (var index = 0; index < this.lights.length; index++) {
  16983. if (this.lights[index].uniqueId === uniqueId) {
  16984. return this.lights[index];
  16985. }
  16986. }
  16987. return null;
  16988. };
  16989. /**
  16990. * get a particle system by id
  16991. * @param id {number} the particle system id
  16992. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16993. */
  16994. Scene.prototype.getParticleSystemByID = function (id) {
  16995. for (var index = 0; index < this.particleSystems.length; index++) {
  16996. if (this.particleSystems[index].id === id) {
  16997. return this.particleSystems[index];
  16998. }
  16999. }
  17000. return null;
  17001. };
  17002. /**
  17003. * get a geometry using its ID
  17004. * @param {string} the geometry's id
  17005. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17006. */
  17007. Scene.prototype.getGeometryByID = function (id) {
  17008. for (var index = 0; index < this._geometries.length; index++) {
  17009. if (this._geometries[index].id === id) {
  17010. return this._geometries[index];
  17011. }
  17012. }
  17013. return null;
  17014. };
  17015. /**
  17016. * add a new geometry to this scene.
  17017. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17018. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17019. * @return {boolean} was the geometry added or not
  17020. */
  17021. Scene.prototype.pushGeometry = function (geometry, force) {
  17022. if (!force && this.getGeometryByID(geometry.id)) {
  17023. return false;
  17024. }
  17025. this._geometries.push(geometry);
  17026. //notify the collision coordinator
  17027. if (this.collisionCoordinator) {
  17028. this.collisionCoordinator.onGeometryAdded(geometry);
  17029. }
  17030. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17031. return true;
  17032. };
  17033. /**
  17034. * Removes an existing geometry
  17035. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17036. * @return {boolean} was the geometry removed or not
  17037. */
  17038. Scene.prototype.removeGeometry = function (geometry) {
  17039. var index = this._geometries.indexOf(geometry);
  17040. if (index > -1) {
  17041. this._geometries.splice(index, 1);
  17042. //notify the collision coordinator
  17043. if (this.collisionCoordinator) {
  17044. this.collisionCoordinator.onGeometryDeleted(geometry);
  17045. }
  17046. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17047. return true;
  17048. }
  17049. return false;
  17050. };
  17051. Scene.prototype.getGeometries = function () {
  17052. return this._geometries;
  17053. };
  17054. /**
  17055. * Get the first added mesh found of a given ID
  17056. * @param {string} id - the id to search for
  17057. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17058. */
  17059. Scene.prototype.getMeshByID = function (id) {
  17060. for (var index = 0; index < this.meshes.length; index++) {
  17061. if (this.meshes[index].id === id) {
  17062. return this.meshes[index];
  17063. }
  17064. }
  17065. return null;
  17066. };
  17067. Scene.prototype.getMeshesByID = function (id) {
  17068. return this.meshes.filter(function (m) {
  17069. return m.id === id;
  17070. });
  17071. };
  17072. /**
  17073. * Get a mesh with its auto-generated unique id
  17074. * @param {number} uniqueId - the unique id to search for
  17075. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17076. */
  17077. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17078. for (var index = 0; index < this.meshes.length; index++) {
  17079. if (this.meshes[index].uniqueId === uniqueId) {
  17080. return this.meshes[index];
  17081. }
  17082. }
  17083. return null;
  17084. };
  17085. /**
  17086. * Get a the last added mesh found of a given ID
  17087. * @param {string} id - the id to search for
  17088. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17089. */
  17090. Scene.prototype.getLastMeshByID = function (id) {
  17091. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17092. if (this.meshes[index].id === id) {
  17093. return this.meshes[index];
  17094. }
  17095. }
  17096. return null;
  17097. };
  17098. /**
  17099. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17100. * @param {string} id - the id to search for
  17101. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17102. */
  17103. Scene.prototype.getLastEntryByID = function (id) {
  17104. var index;
  17105. for (index = this.meshes.length - 1; index >= 0; index--) {
  17106. if (this.meshes[index].id === id) {
  17107. return this.meshes[index];
  17108. }
  17109. }
  17110. for (index = this.cameras.length - 1; index >= 0; index--) {
  17111. if (this.cameras[index].id === id) {
  17112. return this.cameras[index];
  17113. }
  17114. }
  17115. for (index = this.lights.length - 1; index >= 0; index--) {
  17116. if (this.lights[index].id === id) {
  17117. return this.lights[index];
  17118. }
  17119. }
  17120. return null;
  17121. };
  17122. Scene.prototype.getNodeByID = function (id) {
  17123. var mesh = this.getMeshByID(id);
  17124. if (mesh) {
  17125. return mesh;
  17126. }
  17127. var light = this.getLightByID(id);
  17128. if (light) {
  17129. return light;
  17130. }
  17131. var camera = this.getCameraByID(id);
  17132. if (camera) {
  17133. return camera;
  17134. }
  17135. var bone = this.getBoneByID(id);
  17136. return bone;
  17137. };
  17138. Scene.prototype.getNodeByName = function (name) {
  17139. var mesh = this.getMeshByName(name);
  17140. if (mesh) {
  17141. return mesh;
  17142. }
  17143. var light = this.getLightByName(name);
  17144. if (light) {
  17145. return light;
  17146. }
  17147. var camera = this.getCameraByName(name);
  17148. if (camera) {
  17149. return camera;
  17150. }
  17151. var bone = this.getBoneByName(name);
  17152. return bone;
  17153. };
  17154. Scene.prototype.getMeshByName = function (name) {
  17155. for (var index = 0; index < this.meshes.length; index++) {
  17156. if (this.meshes[index].name === name) {
  17157. return this.meshes[index];
  17158. }
  17159. }
  17160. return null;
  17161. };
  17162. Scene.prototype.getSoundByName = function (name) {
  17163. var index;
  17164. if (BABYLON.AudioEngine) {
  17165. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17166. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17167. return this.mainSoundTrack.soundCollection[index];
  17168. }
  17169. }
  17170. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17171. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17172. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17173. return this.soundTracks[sdIndex].soundCollection[index];
  17174. }
  17175. }
  17176. }
  17177. }
  17178. return null;
  17179. };
  17180. Scene.prototype.getLastSkeletonByID = function (id) {
  17181. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17182. if (this.skeletons[index].id === id) {
  17183. return this.skeletons[index];
  17184. }
  17185. }
  17186. return null;
  17187. };
  17188. Scene.prototype.getSkeletonById = function (id) {
  17189. for (var index = 0; index < this.skeletons.length; index++) {
  17190. if (this.skeletons[index].id === id) {
  17191. return this.skeletons[index];
  17192. }
  17193. }
  17194. return null;
  17195. };
  17196. Scene.prototype.getSkeletonByName = function (name) {
  17197. for (var index = 0; index < this.skeletons.length; index++) {
  17198. if (this.skeletons[index].name === name) {
  17199. return this.skeletons[index];
  17200. }
  17201. }
  17202. return null;
  17203. };
  17204. Scene.prototype.getMorphTargetManagerById = function (id) {
  17205. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17206. if (this.morphTargetManagers[index].uniqueId === id) {
  17207. return this.morphTargetManagers[index];
  17208. }
  17209. }
  17210. return null;
  17211. };
  17212. Scene.prototype.isActiveMesh = function (mesh) {
  17213. return (this._activeMeshes.indexOf(mesh) !== -1);
  17214. };
  17215. /**
  17216. * Return a the first highlight layer of the scene with a given name.
  17217. * @param name The name of the highlight layer to look for.
  17218. * @return The highlight layer if found otherwise null.
  17219. */
  17220. Scene.prototype.getHighlightLayerByName = function (name) {
  17221. for (var index = 0; index < this.highlightLayers.length; index++) {
  17222. if (this.highlightLayers[index].name === name) {
  17223. return this.highlightLayers[index];
  17224. }
  17225. }
  17226. return null;
  17227. };
  17228. Object.defineProperty(Scene.prototype, "uid", {
  17229. /**
  17230. * Return a unique id as a string which can serve as an identifier for the scene
  17231. */
  17232. get: function () {
  17233. if (!this._uid) {
  17234. this._uid = BABYLON.Tools.RandomId();
  17235. }
  17236. return this._uid;
  17237. },
  17238. enumerable: true,
  17239. configurable: true
  17240. });
  17241. /**
  17242. * Add an externaly attached data from its key.
  17243. * This method call will fail and return false, if such key already exists.
  17244. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17245. * @param key the unique key that identifies the data
  17246. * @param data the data object to associate to the key for this Engine instance
  17247. * @return true if no such key were already present and the data was added successfully, false otherwise
  17248. */
  17249. Scene.prototype.addExternalData = function (key, data) {
  17250. if (!this._externalData) {
  17251. this._externalData = new BABYLON.StringDictionary();
  17252. }
  17253. return this._externalData.add(key, data);
  17254. };
  17255. /**
  17256. * Get an externaly attached data from its key
  17257. * @param key the unique key that identifies the data
  17258. * @return the associated data, if present (can be null), or undefined if not present
  17259. */
  17260. Scene.prototype.getExternalData = function (key) {
  17261. if (!this._externalData) {
  17262. return null;
  17263. }
  17264. return this._externalData.get(key);
  17265. };
  17266. /**
  17267. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17268. * @param key the unique key that identifies the data
  17269. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17270. * @return the associated data, can be null if the factory returned null.
  17271. */
  17272. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17273. if (!this._externalData) {
  17274. this._externalData = new BABYLON.StringDictionary();
  17275. }
  17276. return this._externalData.getOrAddWithFactory(key, factory);
  17277. };
  17278. /**
  17279. * Remove an externaly attached data from the Engine instance
  17280. * @param key the unique key that identifies the data
  17281. * @return true if the data was successfully removed, false if it doesn't exist
  17282. */
  17283. Scene.prototype.removeExternalData = function (key) {
  17284. return this._externalData.remove(key);
  17285. };
  17286. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17287. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17288. var material = subMesh.getMaterial();
  17289. if (mesh.showSubMeshesBoundingBox) {
  17290. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17291. }
  17292. if (material) {
  17293. // Render targets
  17294. if (material.getRenderTargetTextures) {
  17295. if (this._processedMaterials.indexOf(material) === -1) {
  17296. this._processedMaterials.push(material);
  17297. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17298. }
  17299. }
  17300. // Dispatch
  17301. this._activeIndices.addCount(subMesh.indexCount, false);
  17302. this._renderingManager.dispatch(subMesh);
  17303. }
  17304. }
  17305. };
  17306. Scene.prototype._isInIntermediateRendering = function () {
  17307. return this._intermediateRendering;
  17308. };
  17309. Scene.prototype._evaluateActiveMeshes = function () {
  17310. this.activeCamera._activeMeshes.reset();
  17311. this._activeMeshes.reset();
  17312. this._renderingManager.reset();
  17313. this._processedMaterials.reset();
  17314. this._activeParticleSystems.reset();
  17315. this._activeSkeletons.reset();
  17316. this._softwareSkinnedMeshes.reset();
  17317. if (this._boundingBoxRenderer) {
  17318. this._boundingBoxRenderer.reset();
  17319. }
  17320. // Meshes
  17321. var meshes;
  17322. var len;
  17323. if (this._selectionOctree) {
  17324. var selection = this._selectionOctree.select(this._frustumPlanes);
  17325. meshes = selection.data;
  17326. len = selection.length;
  17327. }
  17328. else {
  17329. len = this.meshes.length;
  17330. meshes = this.meshes;
  17331. }
  17332. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17333. var mesh = meshes[meshIndex];
  17334. if (mesh.isBlocked) {
  17335. continue;
  17336. }
  17337. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17338. if (!mesh.isReady() || !mesh.isEnabled()) {
  17339. continue;
  17340. }
  17341. mesh.computeWorldMatrix();
  17342. // Intersections
  17343. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17344. this._meshesForIntersections.pushNoDuplicate(mesh);
  17345. }
  17346. // Switch to current LOD
  17347. var meshLOD = mesh.getLOD(this.activeCamera);
  17348. if (!meshLOD) {
  17349. continue;
  17350. }
  17351. mesh._preActivate();
  17352. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17353. this._activeMeshes.push(mesh);
  17354. this.activeCamera._activeMeshes.push(mesh);
  17355. mesh._activate(this._renderId);
  17356. this._activeMesh(mesh, meshLOD);
  17357. }
  17358. }
  17359. // Particle systems
  17360. this._particlesDuration.beginMonitoring();
  17361. var beforeParticlesDate = BABYLON.Tools.Now;
  17362. if (this.particlesEnabled) {
  17363. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17364. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17365. var particleSystem = this.particleSystems[particleIndex];
  17366. if (!particleSystem.isStarted()) {
  17367. continue;
  17368. }
  17369. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17370. this._activeParticleSystems.push(particleSystem);
  17371. particleSystem.animate();
  17372. this._renderingManager.dispatchParticles(particleSystem);
  17373. }
  17374. }
  17375. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17376. }
  17377. this._particlesDuration.endMonitoring(false);
  17378. };
  17379. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17380. if (mesh.skeleton && this.skeletonsEnabled) {
  17381. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17382. mesh.skeleton.prepare();
  17383. }
  17384. if (!mesh.computeBonesUsingShaders) {
  17385. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17386. }
  17387. }
  17388. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17389. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17390. }
  17391. if (mesh && mesh.subMeshes) {
  17392. // Submeshes Octrees
  17393. var len;
  17394. var subMeshes;
  17395. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17396. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17397. len = intersections.length;
  17398. subMeshes = intersections.data;
  17399. }
  17400. else {
  17401. subMeshes = mesh.subMeshes;
  17402. len = subMeshes.length;
  17403. }
  17404. for (var subIndex = 0; subIndex < len; subIndex++) {
  17405. var subMesh = subMeshes[subIndex];
  17406. this._evaluateSubMesh(subMesh, mesh);
  17407. }
  17408. }
  17409. };
  17410. Scene.prototype.updateTransformMatrix = function (force) {
  17411. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17412. };
  17413. Scene.prototype._renderForCamera = function (camera) {
  17414. var engine = this._engine;
  17415. var startTime = BABYLON.Tools.Now;
  17416. this.activeCamera = camera;
  17417. if (!this.activeCamera)
  17418. throw new Error("Active camera not set");
  17419. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17420. // Viewport
  17421. engine.setViewport(this.activeCamera.viewport);
  17422. // Camera
  17423. this.resetCachedMaterial();
  17424. this._renderId++;
  17425. this.updateTransformMatrix();
  17426. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17427. // Meshes
  17428. this._evaluateActiveMeshesDuration.beginMonitoring();
  17429. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17430. this._evaluateActiveMeshes();
  17431. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17432. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17433. // Software skinning
  17434. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17435. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17436. mesh.applySkeleton(mesh.skeleton);
  17437. }
  17438. // Render targets
  17439. this._renderTargetsDuration.beginMonitoring();
  17440. var needsRestoreFrameBuffer = false;
  17441. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17442. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17443. this._intermediateRendering = true;
  17444. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17445. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17446. var renderTarget = this._renderTargets.data[renderIndex];
  17447. if (renderTarget._shouldRender()) {
  17448. this._renderId++;
  17449. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17450. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17451. }
  17452. }
  17453. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17454. this._intermediateRendering = false;
  17455. this._renderId++;
  17456. needsRestoreFrameBuffer = true; // Restore back buffer
  17457. }
  17458. // Render HighlightLayer Texture
  17459. var stencilState = this._engine.getStencilBuffer();
  17460. var renderhighlights = false;
  17461. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17462. this._intermediateRendering = true;
  17463. for (var i = 0; i < this.highlightLayers.length; i++) {
  17464. var highlightLayer = this.highlightLayers[i];
  17465. if (highlightLayer.shouldRender() &&
  17466. (!highlightLayer.camera ||
  17467. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17468. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17469. renderhighlights = true;
  17470. var renderTarget = highlightLayer._mainTexture;
  17471. if (renderTarget._shouldRender()) {
  17472. this._renderId++;
  17473. renderTarget.render(false, false);
  17474. needsRestoreFrameBuffer = true;
  17475. }
  17476. }
  17477. }
  17478. this._intermediateRendering = false;
  17479. this._renderId++;
  17480. }
  17481. if (needsRestoreFrameBuffer) {
  17482. if (this.offscreenRenderTarget) {
  17483. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17484. }
  17485. else {
  17486. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17487. }
  17488. }
  17489. this._renderTargetsDuration.endMonitoring(false);
  17490. // Prepare Frame
  17491. this.postProcessManager._prepareFrame();
  17492. this._renderDuration.beginMonitoring();
  17493. // Backgrounds
  17494. var layerIndex;
  17495. var layer;
  17496. if (this.layers.length) {
  17497. engine.setDepthBuffer(false);
  17498. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17499. layer = this.layers[layerIndex];
  17500. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17501. layer.render();
  17502. }
  17503. }
  17504. engine.setDepthBuffer(true);
  17505. }
  17506. // Render
  17507. BABYLON.Tools.StartPerformanceCounter("Main render");
  17508. // Activate HighlightLayer stencil
  17509. if (renderhighlights) {
  17510. this._engine.setStencilBuffer(true);
  17511. }
  17512. this._renderingManager.render(null, null, true, true);
  17513. // Restore HighlightLayer stencil
  17514. if (renderhighlights) {
  17515. this._engine.setStencilBuffer(stencilState);
  17516. }
  17517. BABYLON.Tools.EndPerformanceCounter("Main render");
  17518. // Bounding boxes
  17519. if (this._boundingBoxRenderer) {
  17520. this._boundingBoxRenderer.render();
  17521. }
  17522. // Lens flares
  17523. if (this.lensFlaresEnabled) {
  17524. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17525. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17526. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17527. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17528. lensFlareSystem.render();
  17529. }
  17530. }
  17531. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17532. }
  17533. // Foregrounds
  17534. if (this.layers.length) {
  17535. engine.setDepthBuffer(false);
  17536. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17537. layer = this.layers[layerIndex];
  17538. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17539. layer.render();
  17540. }
  17541. }
  17542. engine.setDepthBuffer(true);
  17543. }
  17544. // Highlight Layer
  17545. if (renderhighlights) {
  17546. engine.setDepthBuffer(false);
  17547. for (var i = 0; i < this.highlightLayers.length; i++) {
  17548. if (this.highlightLayers[i].shouldRender()) {
  17549. this.highlightLayers[i].render();
  17550. }
  17551. }
  17552. engine.setDepthBuffer(true);
  17553. }
  17554. this._renderDuration.endMonitoring(false);
  17555. // Finalize frame
  17556. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17557. // Update camera
  17558. this.activeCamera._updateFromScene();
  17559. // Reset some special arrays
  17560. this._renderTargets.reset();
  17561. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17562. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17563. };
  17564. Scene.prototype._processSubCameras = function (camera) {
  17565. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17566. this._renderForCamera(camera);
  17567. return;
  17568. }
  17569. // rig cameras
  17570. for (var index = 0; index < camera._rigCameras.length; index++) {
  17571. this._renderForCamera(camera._rigCameras[index]);
  17572. }
  17573. this.activeCamera = camera;
  17574. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17575. // Update camera
  17576. this.activeCamera._updateFromScene();
  17577. };
  17578. Scene.prototype._checkIntersections = function () {
  17579. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17580. var sourceMesh = this._meshesForIntersections.data[index];
  17581. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17582. var action = sourceMesh.actionManager.actions[actionIndex];
  17583. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17584. var parameters = action.getTriggerParameter();
  17585. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17586. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17587. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17588. if (areIntersecting && currentIntersectionInProgress === -1) {
  17589. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17590. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17591. sourceMesh._intersectionsInProgress.push(otherMesh);
  17592. }
  17593. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17594. sourceMesh._intersectionsInProgress.push(otherMesh);
  17595. }
  17596. }
  17597. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17598. //They intersected, and now they don't.
  17599. //is this trigger an exit trigger? execute an event.
  17600. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17601. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17602. }
  17603. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17604. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17605. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17606. }
  17607. }
  17608. }
  17609. }
  17610. }
  17611. };
  17612. Scene.prototype.render = function () {
  17613. if (this.isDisposed) {
  17614. return;
  17615. }
  17616. this._lastFrameDuration.beginMonitoring();
  17617. this._particlesDuration.fetchNewFrame();
  17618. this._spritesDuration.fetchNewFrame();
  17619. this._activeParticles.fetchNewFrame();
  17620. this._renderDuration.fetchNewFrame();
  17621. this._renderTargetsDuration.fetchNewFrame();
  17622. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17623. this._totalVertices.fetchNewFrame();
  17624. this._activeIndices.fetchNewFrame();
  17625. this._activeBones.fetchNewFrame();
  17626. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17627. this._meshesForIntersections.reset();
  17628. this.resetCachedMaterial();
  17629. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17630. // Actions
  17631. if (this.actionManager) {
  17632. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17633. }
  17634. //Simplification Queue
  17635. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17636. this.simplificationQueue.executeNext();
  17637. }
  17638. // Animations
  17639. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17640. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17641. this._animate();
  17642. // Physics
  17643. if (this._physicsEngine) {
  17644. BABYLON.Tools.StartPerformanceCounter("Physics");
  17645. this._physicsEngine._step(deltaTime / 1000.0);
  17646. BABYLON.Tools.EndPerformanceCounter("Physics");
  17647. }
  17648. // Before render
  17649. this.onBeforeRenderObservable.notifyObservers(this);
  17650. // Customs render targets
  17651. this._renderTargetsDuration.beginMonitoring();
  17652. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17653. var engine = this.getEngine();
  17654. var currentActiveCamera = this.activeCamera;
  17655. if (this.renderTargetsEnabled) {
  17656. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17657. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17658. var renderTarget = this.customRenderTargets[customIndex];
  17659. if (renderTarget._shouldRender()) {
  17660. this._renderId++;
  17661. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17662. if (!this.activeCamera)
  17663. throw new Error("Active camera not set");
  17664. // Viewport
  17665. engine.setViewport(this.activeCamera.viewport);
  17666. // Camera
  17667. this.updateTransformMatrix();
  17668. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17669. }
  17670. }
  17671. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17672. this._renderId++;
  17673. }
  17674. if (this.offscreenRenderTarget) {
  17675. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17676. }
  17677. else {
  17678. // Restore back buffer
  17679. if (this.customRenderTargets.length > 0) {
  17680. engine.restoreDefaultFramebuffer();
  17681. }
  17682. }
  17683. this._renderTargetsDuration.endMonitoring();
  17684. this.activeCamera = currentActiveCamera;
  17685. // Procedural textures
  17686. if (this.proceduralTexturesEnabled) {
  17687. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17688. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17689. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17690. if (proceduralTexture._shouldRender()) {
  17691. proceduralTexture.render();
  17692. }
  17693. }
  17694. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17695. }
  17696. // Clear
  17697. if (this.autoClearDepthAndStencil || this.autoClear) {
  17698. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17699. }
  17700. // Shadows
  17701. if (this.shadowsEnabled) {
  17702. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17703. var light = this.lights[lightIndex];
  17704. var shadowGenerator = light.getShadowGenerator();
  17705. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17706. var shadowMap = shadowGenerator.getShadowMap();
  17707. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17708. this._renderTargets.push(shadowMap);
  17709. }
  17710. }
  17711. }
  17712. }
  17713. // Depth renderer
  17714. if (this._depthRenderer) {
  17715. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17716. }
  17717. // Geometry renderer
  17718. if (this._geometryBufferRenderer) {
  17719. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17720. }
  17721. // RenderPipeline
  17722. if (this._postProcessRenderPipelineManager) {
  17723. this._postProcessRenderPipelineManager.update();
  17724. }
  17725. // Multi-cameras?
  17726. if (this.activeCameras.length > 0) {
  17727. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17728. if (cameraIndex > 0) {
  17729. this._engine.clear(null, false, true, true);
  17730. }
  17731. this._processSubCameras(this.activeCameras[cameraIndex]);
  17732. }
  17733. }
  17734. else {
  17735. if (!this.activeCamera) {
  17736. throw new Error("No camera defined");
  17737. }
  17738. this._processSubCameras(this.activeCamera);
  17739. }
  17740. // Intersection checks
  17741. this._checkIntersections();
  17742. // Update the audio listener attached to the camera
  17743. if (BABYLON.AudioEngine) {
  17744. this._updateAudioParameters();
  17745. }
  17746. // After render
  17747. if (this.afterRender) {
  17748. this.afterRender();
  17749. }
  17750. this.onAfterRenderObservable.notifyObservers(this);
  17751. // Cleaning
  17752. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17753. this._toBeDisposed.data[index].dispose();
  17754. this._toBeDisposed[index] = null;
  17755. }
  17756. this._toBeDisposed.reset();
  17757. if (this.dumpNextRenderTargets) {
  17758. this.dumpNextRenderTargets = false;
  17759. }
  17760. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17761. this._lastFrameDuration.endMonitoring();
  17762. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17763. this._totalLightsCounter.addCount(this.lights.length, true);
  17764. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17765. this._totalTexturesCounter.addCount(this.textures.length, true);
  17766. this._activeBones.addCount(0, true);
  17767. this._activeIndices.addCount(0, true);
  17768. this._activeParticles.addCount(0, true);
  17769. };
  17770. Scene.prototype._updateAudioParameters = function () {
  17771. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17772. return;
  17773. }
  17774. var listeningCamera;
  17775. var audioEngine = BABYLON.Engine.audioEngine;
  17776. if (this.activeCameras.length > 0) {
  17777. listeningCamera = this.activeCameras[0];
  17778. }
  17779. else {
  17780. listeningCamera = this.activeCamera;
  17781. }
  17782. if (listeningCamera && audioEngine.canUseWebAudio) {
  17783. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17784. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17785. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17786. cameraDirection.normalize();
  17787. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17788. var i;
  17789. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17790. var sound = this.mainSoundTrack.soundCollection[i];
  17791. if (sound.useCustomAttenuation) {
  17792. sound.updateDistanceFromListener();
  17793. }
  17794. }
  17795. for (i = 0; i < this.soundTracks.length; i++) {
  17796. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17797. sound = this.soundTracks[i].soundCollection[j];
  17798. if (sound.useCustomAttenuation) {
  17799. sound.updateDistanceFromListener();
  17800. }
  17801. }
  17802. }
  17803. }
  17804. };
  17805. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17806. // Audio
  17807. get: function () {
  17808. return this._audioEnabled;
  17809. },
  17810. set: function (value) {
  17811. this._audioEnabled = value;
  17812. if (BABYLON.AudioEngine) {
  17813. if (this._audioEnabled) {
  17814. this._enableAudio();
  17815. }
  17816. else {
  17817. this._disableAudio();
  17818. }
  17819. }
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. Scene.prototype._disableAudio = function () {
  17825. var i;
  17826. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17827. this.mainSoundTrack.soundCollection[i].pause();
  17828. }
  17829. for (i = 0; i < this.soundTracks.length; i++) {
  17830. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17831. this.soundTracks[i].soundCollection[j].pause();
  17832. }
  17833. }
  17834. };
  17835. Scene.prototype._enableAudio = function () {
  17836. var i;
  17837. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17838. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17839. this.mainSoundTrack.soundCollection[i].play();
  17840. }
  17841. }
  17842. for (i = 0; i < this.soundTracks.length; i++) {
  17843. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17844. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17845. this.soundTracks[i].soundCollection[j].play();
  17846. }
  17847. }
  17848. }
  17849. };
  17850. Object.defineProperty(Scene.prototype, "headphone", {
  17851. get: function () {
  17852. return this._headphone;
  17853. },
  17854. set: function (value) {
  17855. this._headphone = value;
  17856. if (BABYLON.AudioEngine) {
  17857. if (this._headphone) {
  17858. this._switchAudioModeForHeadphones();
  17859. }
  17860. else {
  17861. this._switchAudioModeForNormalSpeakers();
  17862. }
  17863. }
  17864. },
  17865. enumerable: true,
  17866. configurable: true
  17867. });
  17868. Scene.prototype._switchAudioModeForHeadphones = function () {
  17869. this.mainSoundTrack.switchPanningModelToHRTF();
  17870. for (var i = 0; i < this.soundTracks.length; i++) {
  17871. this.soundTracks[i].switchPanningModelToHRTF();
  17872. }
  17873. };
  17874. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17875. this.mainSoundTrack.switchPanningModelToEqualPower();
  17876. for (var i = 0; i < this.soundTracks.length; i++) {
  17877. this.soundTracks[i].switchPanningModelToEqualPower();
  17878. }
  17879. };
  17880. Scene.prototype.enableDepthRenderer = function () {
  17881. if (this._depthRenderer) {
  17882. return this._depthRenderer;
  17883. }
  17884. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17885. return this._depthRenderer;
  17886. };
  17887. Scene.prototype.disableDepthRenderer = function () {
  17888. if (!this._depthRenderer) {
  17889. return;
  17890. }
  17891. this._depthRenderer.dispose();
  17892. this._depthRenderer = null;
  17893. };
  17894. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17895. if (ratio === void 0) { ratio = 1; }
  17896. if (this._geometryBufferRenderer) {
  17897. return this._geometryBufferRenderer;
  17898. }
  17899. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17900. if (!this._geometryBufferRenderer.isSupported) {
  17901. this._geometryBufferRenderer = null;
  17902. }
  17903. return this._geometryBufferRenderer;
  17904. };
  17905. Scene.prototype.disableGeometryBufferRenderer = function () {
  17906. if (!this._geometryBufferRenderer) {
  17907. return;
  17908. }
  17909. this._geometryBufferRenderer.dispose();
  17910. this._geometryBufferRenderer = null;
  17911. };
  17912. Scene.prototype.freezeMaterials = function () {
  17913. for (var i = 0; i < this.materials.length; i++) {
  17914. this.materials[i].freeze();
  17915. }
  17916. };
  17917. Scene.prototype.unfreezeMaterials = function () {
  17918. for (var i = 0; i < this.materials.length; i++) {
  17919. this.materials[i].unfreeze();
  17920. }
  17921. };
  17922. Scene.prototype.dispose = function () {
  17923. this.beforeRender = null;
  17924. this.afterRender = null;
  17925. this.skeletons = [];
  17926. this.morphTargetManagers = [];
  17927. this.importedMeshesFiles = new Array();
  17928. if (this._depthRenderer) {
  17929. this._depthRenderer.dispose();
  17930. }
  17931. // Smart arrays
  17932. if (this.activeCamera) {
  17933. this.activeCamera._activeMeshes.dispose();
  17934. this.activeCamera = null;
  17935. }
  17936. this._activeMeshes.dispose();
  17937. this._renderingManager.dispose();
  17938. this._processedMaterials.dispose();
  17939. this._activeParticleSystems.dispose();
  17940. this._activeSkeletons.dispose();
  17941. this._softwareSkinnedMeshes.dispose();
  17942. if (this._boundingBoxRenderer) {
  17943. this._boundingBoxRenderer.dispose();
  17944. }
  17945. this._meshesForIntersections.dispose();
  17946. this._toBeDisposed.dispose();
  17947. // Debug layer
  17948. if (this._debugLayer) {
  17949. this._debugLayer.hide();
  17950. }
  17951. // Events
  17952. this.onDisposeObservable.notifyObservers(this);
  17953. this.onDisposeObservable.clear();
  17954. this.onBeforeRenderObservable.clear();
  17955. this.onAfterRenderObservable.clear();
  17956. this.detachControl();
  17957. // Release sounds & sounds tracks
  17958. if (BABYLON.AudioEngine) {
  17959. this.disposeSounds();
  17960. }
  17961. // Detach cameras
  17962. var canvas = this._engine.getRenderingCanvas();
  17963. var index;
  17964. for (index = 0; index < this.cameras.length; index++) {
  17965. this.cameras[index].detachControl(canvas);
  17966. }
  17967. // Release lights
  17968. while (this.lights.length) {
  17969. this.lights[0].dispose();
  17970. }
  17971. // Release meshes
  17972. while (this.meshes.length) {
  17973. this.meshes[0].dispose(true);
  17974. }
  17975. // Release cameras
  17976. while (this.cameras.length) {
  17977. this.cameras[0].dispose();
  17978. }
  17979. // Release materials
  17980. while (this.materials.length) {
  17981. this.materials[0].dispose();
  17982. }
  17983. // Release particles
  17984. while (this.particleSystems.length) {
  17985. this.particleSystems[0].dispose();
  17986. }
  17987. // Release sprites
  17988. while (this.spriteManagers.length) {
  17989. this.spriteManagers[0].dispose();
  17990. }
  17991. // Release layers
  17992. while (this.layers.length) {
  17993. this.layers[0].dispose();
  17994. }
  17995. while (this.highlightLayers.length) {
  17996. this.highlightLayers[0].dispose();
  17997. }
  17998. // Release textures
  17999. while (this.textures.length) {
  18000. this.textures[0].dispose();
  18001. }
  18002. // Release UBO
  18003. this._sceneUbo.dispose();
  18004. // Post-processes
  18005. this.postProcessManager.dispose();
  18006. // Physics
  18007. if (this._physicsEngine) {
  18008. this.disablePhysicsEngine();
  18009. }
  18010. // Remove from engine
  18011. index = this._engine.scenes.indexOf(this);
  18012. if (index > -1) {
  18013. this._engine.scenes.splice(index, 1);
  18014. }
  18015. this._engine.wipeCaches();
  18016. this._engine = null;
  18017. };
  18018. Object.defineProperty(Scene.prototype, "isDisposed", {
  18019. get: function () {
  18020. return !this._engine;
  18021. },
  18022. enumerable: true,
  18023. configurable: true
  18024. });
  18025. // Release sounds & sounds tracks
  18026. Scene.prototype.disposeSounds = function () {
  18027. this.mainSoundTrack.dispose();
  18028. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18029. this.soundTracks[scIndex].dispose();
  18030. }
  18031. };
  18032. // Octrees
  18033. Scene.prototype.getWorldExtends = function () {
  18034. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18035. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18036. for (var index = 0; index < this.meshes.length; index++) {
  18037. var mesh = this.meshes[index];
  18038. mesh.computeWorldMatrix(true);
  18039. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18040. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18041. BABYLON.Tools.CheckExtends(minBox, min, max);
  18042. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18043. }
  18044. return {
  18045. min: min,
  18046. max: max
  18047. };
  18048. };
  18049. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18050. if (maxCapacity === void 0) { maxCapacity = 64; }
  18051. if (maxDepth === void 0) { maxDepth = 2; }
  18052. if (!this._selectionOctree) {
  18053. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18054. }
  18055. var worldExtends = this.getWorldExtends();
  18056. // Update octree
  18057. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18058. return this._selectionOctree;
  18059. };
  18060. // Picking
  18061. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18062. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18063. var engine = this._engine;
  18064. if (!camera) {
  18065. if (!this.activeCamera)
  18066. throw new Error("Active camera not set");
  18067. camera = this.activeCamera;
  18068. }
  18069. var cameraViewport = camera.viewport;
  18070. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18071. // Moving coordinates to local viewport world
  18072. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18073. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18074. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18075. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18076. };
  18077. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18078. if (!BABYLON.PickingInfo) {
  18079. return null;
  18080. }
  18081. var engine = this._engine;
  18082. if (!camera) {
  18083. if (!this.activeCamera)
  18084. throw new Error("Active camera not set");
  18085. camera = this.activeCamera;
  18086. }
  18087. var cameraViewport = camera.viewport;
  18088. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18089. var identity = BABYLON.Matrix.Identity();
  18090. // Moving coordinates to local viewport world
  18091. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18092. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18093. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18094. };
  18095. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18096. if (!BABYLON.PickingInfo) {
  18097. return null;
  18098. }
  18099. var pickingInfo = null;
  18100. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18101. var mesh = this.meshes[meshIndex];
  18102. if (predicate) {
  18103. if (!predicate(mesh)) {
  18104. continue;
  18105. }
  18106. }
  18107. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18108. continue;
  18109. }
  18110. var world = mesh.getWorldMatrix();
  18111. var ray = rayFunction(world);
  18112. var result = mesh.intersects(ray, fastCheck);
  18113. if (!result || !result.hit)
  18114. continue;
  18115. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18116. continue;
  18117. pickingInfo = result;
  18118. if (fastCheck) {
  18119. break;
  18120. }
  18121. }
  18122. return pickingInfo || new BABYLON.PickingInfo();
  18123. };
  18124. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18125. if (!BABYLON.PickingInfo) {
  18126. return null;
  18127. }
  18128. var pickingInfos = new Array();
  18129. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18130. var mesh = this.meshes[meshIndex];
  18131. if (predicate) {
  18132. if (!predicate(mesh)) {
  18133. continue;
  18134. }
  18135. }
  18136. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18137. continue;
  18138. }
  18139. var world = mesh.getWorldMatrix();
  18140. var ray = rayFunction(world);
  18141. var result = mesh.intersects(ray, false);
  18142. if (!result || !result.hit)
  18143. continue;
  18144. pickingInfos.push(result);
  18145. }
  18146. return pickingInfos;
  18147. };
  18148. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18149. if (!BABYLON.PickingInfo) {
  18150. return null;
  18151. }
  18152. var pickingInfo = null;
  18153. camera = camera || this.activeCamera;
  18154. if (this.spriteManagers.length > 0) {
  18155. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18156. var spriteManager = this.spriteManagers[spriteIndex];
  18157. if (!spriteManager.isPickable) {
  18158. continue;
  18159. }
  18160. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18161. if (!result || !result.hit)
  18162. continue;
  18163. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18164. continue;
  18165. pickingInfo = result;
  18166. if (fastCheck) {
  18167. break;
  18168. }
  18169. }
  18170. }
  18171. return pickingInfo || new BABYLON.PickingInfo();
  18172. };
  18173. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18174. /// <param name="x">X position on screen</param>
  18175. /// <param name="y">Y position on screen</param>
  18176. /// <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>
  18177. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18178. /// <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>
  18179. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18180. var _this = this;
  18181. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18182. };
  18183. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18184. /// <param name="x">X position on screen</param>
  18185. /// <param name="y">Y position on screen</param>
  18186. /// <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>
  18187. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18188. /// <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>
  18189. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18190. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18191. };
  18192. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18193. var _this = this;
  18194. return this._internalPick(function (world) {
  18195. if (!_this._pickWithRayInverseMatrix) {
  18196. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18197. }
  18198. world.invertToRef(_this._pickWithRayInverseMatrix);
  18199. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18200. }, predicate, fastCheck);
  18201. };
  18202. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18203. /// <param name="x">X position on screen</param>
  18204. /// <param name="y">Y position on screen</param>
  18205. /// <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>
  18206. /// <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>
  18207. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18208. var _this = this;
  18209. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18210. };
  18211. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18212. /// <param name="ray">Ray to use</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. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18215. var _this = this;
  18216. return this._internalMultiPick(function (world) {
  18217. if (!_this._pickWithRayInverseMatrix) {
  18218. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18219. }
  18220. world.invertToRef(_this._pickWithRayInverseMatrix);
  18221. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18222. }, predicate);
  18223. };
  18224. Scene.prototype.setPointerOverMesh = function (mesh) {
  18225. if (this._pointerOverMesh === mesh) {
  18226. return;
  18227. }
  18228. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18229. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18230. }
  18231. this._pointerOverMesh = mesh;
  18232. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18233. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18234. }
  18235. };
  18236. Scene.prototype.getPointerOverMesh = function () {
  18237. return this._pointerOverMesh;
  18238. };
  18239. Scene.prototype.setPointerOverSprite = function (sprite) {
  18240. if (this._pointerOverSprite === sprite) {
  18241. return;
  18242. }
  18243. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18244. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18245. }
  18246. this._pointerOverSprite = sprite;
  18247. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18248. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18249. }
  18250. };
  18251. Scene.prototype.getPointerOverSprite = function () {
  18252. return this._pointerOverSprite;
  18253. };
  18254. // Physics
  18255. Scene.prototype.getPhysicsEngine = function () {
  18256. return this._physicsEngine;
  18257. };
  18258. /**
  18259. * Enables physics to the current scene
  18260. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18261. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18262. * @return {boolean} was the physics engine initialized
  18263. */
  18264. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18265. if (this._physicsEngine) {
  18266. return true;
  18267. }
  18268. try {
  18269. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18270. return true;
  18271. }
  18272. catch (e) {
  18273. BABYLON.Tools.Error(e.message);
  18274. return false;
  18275. }
  18276. };
  18277. Scene.prototype.disablePhysicsEngine = function () {
  18278. if (!this._physicsEngine) {
  18279. return;
  18280. }
  18281. this._physicsEngine.dispose();
  18282. this._physicsEngine = undefined;
  18283. };
  18284. Scene.prototype.isPhysicsEnabled = function () {
  18285. return this._physicsEngine !== undefined;
  18286. };
  18287. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18288. var mesh = compound.parts[0].mesh;
  18289. mesh.physicsImpostor.dispose();
  18290. mesh.physicsImpostor = null;
  18291. };
  18292. // Misc.
  18293. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18294. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18295. // Light
  18296. if (this.lights.length === 0) {
  18297. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18298. }
  18299. // Camera
  18300. if (!this.activeCamera) {
  18301. var worldExtends = this.getWorldExtends();
  18302. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18303. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18304. var camera;
  18305. var radius = worldSize.length() * 1.5;
  18306. if (createArcRotateCamera) {
  18307. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18308. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18309. arcRotateCamera.wheelPrecision = 100 / radius;
  18310. camera = arcRotateCamera;
  18311. }
  18312. else {
  18313. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18314. freeCamera.setTarget(worldCenter);
  18315. camera = freeCamera;
  18316. }
  18317. camera.minZ = radius * 0.01;
  18318. camera.maxZ = radius * 100;
  18319. camera.speed = radius * 0.2;
  18320. this.activeCamera = camera;
  18321. }
  18322. };
  18323. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18324. if (pbr === void 0) { pbr = false; }
  18325. if (environmentTexture) {
  18326. this.environmentTexture = environmentTexture;
  18327. }
  18328. if (!this.environmentTexture) {
  18329. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18330. return;
  18331. }
  18332. if (!this.environmentTexture) {
  18333. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18334. return;
  18335. }
  18336. // Skybox
  18337. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18338. if (pbr) {
  18339. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18340. hdrSkyboxMaterial.backFaceCulling = false;
  18341. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18342. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18343. hdrSkyboxMaterial.microSurface = 1.0;
  18344. hdrSkyboxMaterial.disableLighting = true;
  18345. hdrSkybox.infiniteDistance = true;
  18346. hdrSkybox.material = hdrSkyboxMaterial;
  18347. }
  18348. else {
  18349. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18350. skyboxMaterial.backFaceCulling = false;
  18351. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18352. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18353. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18354. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18355. skyboxMaterial.disableLighting = true;
  18356. hdrSkybox.infiniteDistance = true;
  18357. hdrSkybox.material = skyboxMaterial;
  18358. }
  18359. return hdrSkybox;
  18360. };
  18361. // Tags
  18362. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18363. if (tagsQuery === undefined) {
  18364. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18365. return list;
  18366. }
  18367. var listByTags = [];
  18368. forEach = forEach || (function (item) { return; });
  18369. for (var i in list) {
  18370. var item = list[i];
  18371. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18372. listByTags.push(item);
  18373. forEach(item);
  18374. }
  18375. }
  18376. return listByTags;
  18377. };
  18378. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18379. return this._getByTags(this.meshes, tagsQuery, forEach);
  18380. };
  18381. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18382. return this._getByTags(this.cameras, tagsQuery, forEach);
  18383. };
  18384. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18385. return this._getByTags(this.lights, tagsQuery, forEach);
  18386. };
  18387. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18388. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18389. };
  18390. /**
  18391. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18392. * This allowed control for front to back rendering or reversly depending of the special needs.
  18393. *
  18394. * @param renderingGroupId The rendering group id corresponding to its index
  18395. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18396. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18397. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18398. */
  18399. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18400. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18401. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18402. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18403. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18404. };
  18405. /**
  18406. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18407. *
  18408. * @param renderingGroupId The rendering group id corresponding to its index
  18409. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18410. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18411. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18412. */
  18413. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18414. if (depth === void 0) { depth = true; }
  18415. if (stencil === void 0) { stencil = true; }
  18416. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18417. };
  18418. /**
  18419. * Will flag all materials as dirty to trigger new shader compilation
  18420. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18421. */
  18422. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18423. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18424. var material = _a[_i];
  18425. if (predicate && !predicate(material)) {
  18426. continue;
  18427. }
  18428. material.markAsDirty(flag);
  18429. }
  18430. };
  18431. return Scene;
  18432. }());
  18433. // Statics
  18434. Scene._FOGMODE_NONE = 0;
  18435. Scene._FOGMODE_EXP = 1;
  18436. Scene._FOGMODE_EXP2 = 2;
  18437. Scene._FOGMODE_LINEAR = 3;
  18438. Scene.MinDeltaTime = 1.0;
  18439. Scene.MaxDeltaTime = 1000.0;
  18440. Scene.DragMovementThreshold = 10; // in pixels
  18441. Scene.LongPressDelay = 500; // in milliseconds
  18442. Scene.DoubleClickDelay = 300; // in milliseconds
  18443. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18444. BABYLON.Scene = Scene;
  18445. })(BABYLON || (BABYLON = {}));
  18446. //# sourceMappingURL=babylon.scene.js.map
  18447. var BABYLON;
  18448. (function (BABYLON) {
  18449. var Buffer = (function () {
  18450. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18451. if (engine instanceof BABYLON.Mesh) {
  18452. this._engine = engine.getScene().getEngine();
  18453. }
  18454. else {
  18455. this._engine = engine;
  18456. }
  18457. this._updatable = updatable;
  18458. this._data = data;
  18459. this._strideSize = stride;
  18460. if (!postponeInternalCreation) {
  18461. this.create();
  18462. }
  18463. this._instanced = instanced;
  18464. }
  18465. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18466. // a lot of these parameters are ignored as they are overriden by the buffer
  18467. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18468. };
  18469. // Properties
  18470. Buffer.prototype.isUpdatable = function () {
  18471. return this._updatable;
  18472. };
  18473. Buffer.prototype.getData = function () {
  18474. return this._data;
  18475. };
  18476. Buffer.prototype.getBuffer = function () {
  18477. return this._buffer;
  18478. };
  18479. Buffer.prototype.getStrideSize = function () {
  18480. return this._strideSize;
  18481. };
  18482. Buffer.prototype.getIsInstanced = function () {
  18483. return this._instanced;
  18484. };
  18485. // Methods
  18486. Buffer.prototype.create = function (data) {
  18487. if (!data && this._buffer) {
  18488. return; // nothing to do
  18489. }
  18490. data = data || this._data;
  18491. if (!this._buffer) {
  18492. if (this._updatable) {
  18493. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18494. this._data = data;
  18495. }
  18496. else {
  18497. this._buffer = this._engine.createVertexBuffer(data);
  18498. }
  18499. }
  18500. else if (this._updatable) {
  18501. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18502. this._data = data;
  18503. }
  18504. };
  18505. Buffer.prototype.update = function (data) {
  18506. this.create(data);
  18507. };
  18508. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18509. if (!this._buffer) {
  18510. return;
  18511. }
  18512. if (this._updatable) {
  18513. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18514. this._data = null;
  18515. }
  18516. };
  18517. Buffer.prototype.dispose = function () {
  18518. if (!this._buffer) {
  18519. return;
  18520. }
  18521. if (this._engine._releaseBuffer(this._buffer)) {
  18522. this._buffer = null;
  18523. }
  18524. };
  18525. return Buffer;
  18526. }());
  18527. BABYLON.Buffer = Buffer;
  18528. })(BABYLON || (BABYLON = {}));
  18529. //# sourceMappingURL=babylon.buffer.js.map
  18530. var BABYLON;
  18531. (function (BABYLON) {
  18532. var VertexBuffer = (function () {
  18533. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18534. if (!stride) {
  18535. // Deduce stride from kind
  18536. switch (kind) {
  18537. case VertexBuffer.PositionKind:
  18538. stride = 3;
  18539. break;
  18540. case VertexBuffer.NormalKind:
  18541. stride = 3;
  18542. break;
  18543. case VertexBuffer.UVKind:
  18544. case VertexBuffer.UV2Kind:
  18545. case VertexBuffer.UV3Kind:
  18546. case VertexBuffer.UV4Kind:
  18547. case VertexBuffer.UV5Kind:
  18548. case VertexBuffer.UV6Kind:
  18549. stride = 2;
  18550. break;
  18551. case VertexBuffer.TangentKind:
  18552. case VertexBuffer.ColorKind:
  18553. stride = 4;
  18554. break;
  18555. case VertexBuffer.MatricesIndicesKind:
  18556. case VertexBuffer.MatricesIndicesExtraKind:
  18557. stride = 4;
  18558. break;
  18559. case VertexBuffer.MatricesWeightsKind:
  18560. case VertexBuffer.MatricesWeightsExtraKind:
  18561. stride = 4;
  18562. break;
  18563. }
  18564. }
  18565. if (data instanceof BABYLON.Buffer) {
  18566. if (!stride) {
  18567. stride = data.getStrideSize();
  18568. }
  18569. this._buffer = data;
  18570. this._ownsBuffer = false;
  18571. }
  18572. else {
  18573. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18574. this._ownsBuffer = true;
  18575. }
  18576. this._stride = stride;
  18577. this._offset = offset ? offset : 0;
  18578. this._size = size ? size : stride;
  18579. this._kind = kind;
  18580. }
  18581. /**
  18582. * Returns the kind of the VertexBuffer (string).
  18583. */
  18584. VertexBuffer.prototype.getKind = function () {
  18585. return this._kind;
  18586. };
  18587. // Properties
  18588. /**
  18589. * Boolean : is the VertexBuffer updatable ?
  18590. */
  18591. VertexBuffer.prototype.isUpdatable = function () {
  18592. return this._buffer.isUpdatable();
  18593. };
  18594. /**
  18595. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18596. */
  18597. VertexBuffer.prototype.getData = function () {
  18598. return this._buffer.getData();
  18599. };
  18600. /**
  18601. * Returns the WebGLBuffer associated to the VertexBuffer.
  18602. */
  18603. VertexBuffer.prototype.getBuffer = function () {
  18604. return this._buffer.getBuffer();
  18605. };
  18606. /**
  18607. * Returns the stride of the VertexBuffer (integer).
  18608. */
  18609. VertexBuffer.prototype.getStrideSize = function () {
  18610. return this._stride;
  18611. };
  18612. /**
  18613. * Returns the offset (integer).
  18614. */
  18615. VertexBuffer.prototype.getOffset = function () {
  18616. return this._offset;
  18617. };
  18618. /**
  18619. * Returns the VertexBuffer total size (integer).
  18620. */
  18621. VertexBuffer.prototype.getSize = function () {
  18622. return this._size;
  18623. };
  18624. /**
  18625. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18626. */
  18627. VertexBuffer.prototype.getIsInstanced = function () {
  18628. return this._buffer.getIsInstanced();
  18629. };
  18630. // Methods
  18631. /**
  18632. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18633. * Returns the created WebGLBuffer.
  18634. */
  18635. VertexBuffer.prototype.create = function (data) {
  18636. return this._buffer.create(data);
  18637. };
  18638. /**
  18639. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18640. * Returns the updated WebGLBuffer.
  18641. */
  18642. VertexBuffer.prototype.update = function (data) {
  18643. return this._buffer.update(data);
  18644. };
  18645. /**
  18646. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18647. * Returns the directly updated WebGLBuffer.
  18648. */
  18649. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18650. return this._buffer.updateDirectly(data, offset);
  18651. };
  18652. /**
  18653. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18654. */
  18655. VertexBuffer.prototype.dispose = function () {
  18656. if (this._ownsBuffer) {
  18657. this._buffer.dispose();
  18658. }
  18659. };
  18660. Object.defineProperty(VertexBuffer, "PositionKind", {
  18661. get: function () {
  18662. return VertexBuffer._PositionKind;
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. Object.defineProperty(VertexBuffer, "NormalKind", {
  18668. get: function () {
  18669. return VertexBuffer._NormalKind;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. Object.defineProperty(VertexBuffer, "TangentKind", {
  18675. get: function () {
  18676. return VertexBuffer._TangentKind;
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. Object.defineProperty(VertexBuffer, "UVKind", {
  18682. get: function () {
  18683. return VertexBuffer._UVKind;
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18689. get: function () {
  18690. return VertexBuffer._UV2Kind;
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18696. get: function () {
  18697. return VertexBuffer._UV3Kind;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18703. get: function () {
  18704. return VertexBuffer._UV4Kind;
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18710. get: function () {
  18711. return VertexBuffer._UV5Kind;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18717. get: function () {
  18718. return VertexBuffer._UV6Kind;
  18719. },
  18720. enumerable: true,
  18721. configurable: true
  18722. });
  18723. Object.defineProperty(VertexBuffer, "ColorKind", {
  18724. get: function () {
  18725. return VertexBuffer._ColorKind;
  18726. },
  18727. enumerable: true,
  18728. configurable: true
  18729. });
  18730. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18731. get: function () {
  18732. return VertexBuffer._MatricesIndicesKind;
  18733. },
  18734. enumerable: true,
  18735. configurable: true
  18736. });
  18737. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18738. get: function () {
  18739. return VertexBuffer._MatricesWeightsKind;
  18740. },
  18741. enumerable: true,
  18742. configurable: true
  18743. });
  18744. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18745. get: function () {
  18746. return VertexBuffer._MatricesIndicesExtraKind;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18752. get: function () {
  18753. return VertexBuffer._MatricesWeightsExtraKind;
  18754. },
  18755. enumerable: true,
  18756. configurable: true
  18757. });
  18758. return VertexBuffer;
  18759. }());
  18760. // Enums
  18761. VertexBuffer._PositionKind = "position";
  18762. VertexBuffer._NormalKind = "normal";
  18763. VertexBuffer._TangentKind = "tangent";
  18764. VertexBuffer._UVKind = "uv";
  18765. VertexBuffer._UV2Kind = "uv2";
  18766. VertexBuffer._UV3Kind = "uv3";
  18767. VertexBuffer._UV4Kind = "uv4";
  18768. VertexBuffer._UV5Kind = "uv5";
  18769. VertexBuffer._UV6Kind = "uv6";
  18770. VertexBuffer._ColorKind = "color";
  18771. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18772. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18773. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18774. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18775. BABYLON.VertexBuffer = VertexBuffer;
  18776. })(BABYLON || (BABYLON = {}));
  18777. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18778. var BABYLON;
  18779. (function (BABYLON) {
  18780. var BaseTexture = (function () {
  18781. function BaseTexture(scene) {
  18782. this._hasAlpha = false;
  18783. this.getAlphaFromRGB = false;
  18784. this.level = 1;
  18785. this.coordinatesIndex = 0;
  18786. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18787. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18788. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18789. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18790. this.isCube = false;
  18791. this.isRenderTarget = false;
  18792. this.animations = new Array();
  18793. /**
  18794. * An event triggered when the texture is disposed.
  18795. * @type {BABYLON.Observable}
  18796. */
  18797. this.onDisposeObservable = new BABYLON.Observable();
  18798. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18799. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18800. this._scene.textures.push(this);
  18801. this._uid = null;
  18802. }
  18803. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18804. get: function () {
  18805. return this._hasAlpha;
  18806. },
  18807. set: function (value) {
  18808. if (this._hasAlpha === value) {
  18809. return;
  18810. }
  18811. this._hasAlpha = value;
  18812. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18813. },
  18814. enumerable: true,
  18815. configurable: true
  18816. });
  18817. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18818. get: function () {
  18819. return this._coordinatesMode;
  18820. },
  18821. set: function (value) {
  18822. if (this._coordinatesMode === value) {
  18823. return;
  18824. }
  18825. this._coordinatesMode = value;
  18826. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18827. },
  18828. enumerable: true,
  18829. configurable: true
  18830. });
  18831. Object.defineProperty(BaseTexture.prototype, "uid", {
  18832. get: function () {
  18833. if (!this._uid) {
  18834. this._uid = BABYLON.Tools.RandomId();
  18835. }
  18836. return this._uid;
  18837. },
  18838. enumerable: true,
  18839. configurable: true
  18840. });
  18841. BaseTexture.prototype.toString = function () {
  18842. return this.name;
  18843. };
  18844. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18845. set: function (callback) {
  18846. if (this._onDisposeObserver) {
  18847. this.onDisposeObservable.remove(this._onDisposeObserver);
  18848. }
  18849. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18850. },
  18851. enumerable: true,
  18852. configurable: true
  18853. });
  18854. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18855. get: function () {
  18856. return true;
  18857. },
  18858. enumerable: true,
  18859. configurable: true
  18860. });
  18861. BaseTexture.prototype.getScene = function () {
  18862. return this._scene;
  18863. };
  18864. BaseTexture.prototype.getTextureMatrix = function () {
  18865. return null;
  18866. };
  18867. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18868. return null;
  18869. };
  18870. BaseTexture.prototype.getInternalTexture = function () {
  18871. return this._texture;
  18872. };
  18873. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18874. return !this.isBlocking || this.isReady();
  18875. };
  18876. BaseTexture.prototype.isReady = function () {
  18877. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18878. this.delayLoad();
  18879. return false;
  18880. }
  18881. if (this._texture) {
  18882. return this._texture.isReady;
  18883. }
  18884. return false;
  18885. };
  18886. BaseTexture.prototype.getSize = function () {
  18887. if (this._texture._width) {
  18888. return new BABYLON.Size(this._texture._width, this._texture._height);
  18889. }
  18890. if (this._texture._size) {
  18891. return new BABYLON.Size(this._texture._size, this._texture._size);
  18892. }
  18893. return BABYLON.Size.Zero();
  18894. };
  18895. BaseTexture.prototype.getBaseSize = function () {
  18896. if (!this.isReady() || !this._texture)
  18897. return BABYLON.Size.Zero();
  18898. if (this._texture._size) {
  18899. return new BABYLON.Size(this._texture._size, this._texture._size);
  18900. }
  18901. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18902. };
  18903. BaseTexture.prototype.scale = function (ratio) {
  18904. };
  18905. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18906. get: function () {
  18907. return false;
  18908. },
  18909. enumerable: true,
  18910. configurable: true
  18911. });
  18912. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18913. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18914. for (var index = 0; index < texturesCache.length; index++) {
  18915. var texturesCacheEntry = texturesCache[index];
  18916. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18917. texturesCache.splice(index, 1);
  18918. return;
  18919. }
  18920. }
  18921. };
  18922. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18923. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18924. for (var index = 0; index < texturesCache.length; index++) {
  18925. var texturesCacheEntry = texturesCache[index];
  18926. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18927. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18928. texturesCacheEntry.references++;
  18929. return texturesCacheEntry;
  18930. }
  18931. }
  18932. }
  18933. return null;
  18934. };
  18935. BaseTexture.prototype.delayLoad = function () {
  18936. };
  18937. BaseTexture.prototype.clone = function () {
  18938. return null;
  18939. };
  18940. BaseTexture.prototype.releaseInternalTexture = function () {
  18941. if (this._texture) {
  18942. this._scene.getEngine().releaseInternalTexture(this._texture);
  18943. delete this._texture;
  18944. }
  18945. };
  18946. BaseTexture.prototype.dispose = function () {
  18947. // Animations
  18948. this.getScene().stopAnimation(this);
  18949. // Remove from scene
  18950. this._scene._removePendingData(this);
  18951. var index = this._scene.textures.indexOf(this);
  18952. if (index >= 0) {
  18953. this._scene.textures.splice(index, 1);
  18954. }
  18955. if (this._texture === undefined) {
  18956. return;
  18957. }
  18958. // Release
  18959. this.releaseInternalTexture();
  18960. // Callback
  18961. this.onDisposeObservable.notifyObservers(this);
  18962. this.onDisposeObservable.clear();
  18963. };
  18964. BaseTexture.prototype.serialize = function () {
  18965. if (!this.name) {
  18966. return null;
  18967. }
  18968. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18969. // Animations
  18970. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18971. return serializationObject;
  18972. };
  18973. return BaseTexture;
  18974. }());
  18975. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18976. __decorate([
  18977. BABYLON.serialize()
  18978. ], BaseTexture.prototype, "name", void 0);
  18979. __decorate([
  18980. BABYLON.serialize("hasAlpha")
  18981. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18982. __decorate([
  18983. BABYLON.serialize()
  18984. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18985. __decorate([
  18986. BABYLON.serialize()
  18987. ], BaseTexture.prototype, "level", void 0);
  18988. __decorate([
  18989. BABYLON.serialize()
  18990. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18991. __decorate([
  18992. BABYLON.serialize("coordinatesMode")
  18993. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18994. __decorate([
  18995. BABYLON.serialize()
  18996. ], BaseTexture.prototype, "wrapU", void 0);
  18997. __decorate([
  18998. BABYLON.serialize()
  18999. ], BaseTexture.prototype, "wrapV", void 0);
  19000. __decorate([
  19001. BABYLON.serialize()
  19002. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19003. __decorate([
  19004. BABYLON.serialize()
  19005. ], BaseTexture.prototype, "isCube", void 0);
  19006. __decorate([
  19007. BABYLON.serialize()
  19008. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19009. BABYLON.BaseTexture = BaseTexture;
  19010. })(BABYLON || (BABYLON = {}));
  19011. //# sourceMappingURL=babylon.baseTexture.js.map
  19012. var BABYLON;
  19013. (function (BABYLON) {
  19014. var Texture = (function (_super) {
  19015. __extends(Texture, _super);
  19016. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19017. if (noMipmap === void 0) { noMipmap = false; }
  19018. if (invertY === void 0) { invertY = true; }
  19019. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19020. if (onLoad === void 0) { onLoad = null; }
  19021. if (onError === void 0) { onError = null; }
  19022. if (buffer === void 0) { buffer = null; }
  19023. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19024. var _this = _super.call(this, scene) || this;
  19025. _this.uOffset = 0;
  19026. _this.vOffset = 0;
  19027. _this.uScale = 1.0;
  19028. _this.vScale = 1.0;
  19029. _this.uAng = 0;
  19030. _this.vAng = 0;
  19031. _this.wAng = 0;
  19032. _this._isBlocking = true;
  19033. _this.name = url;
  19034. _this.url = url;
  19035. _this._noMipmap = noMipmap;
  19036. _this._invertY = invertY;
  19037. _this._samplingMode = samplingMode;
  19038. _this._buffer = buffer;
  19039. _this._deleteBuffer = deleteBuffer;
  19040. _this._format = format;
  19041. scene = _this.getScene();
  19042. var load = function () {
  19043. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19044. _this.onLoadObservable.notifyObservers(true);
  19045. }
  19046. if (onLoad) {
  19047. onLoad();
  19048. }
  19049. if (!_this.isBlocking) {
  19050. scene.resetCachedMaterial();
  19051. }
  19052. };
  19053. if (!url) {
  19054. _this._delayedOnLoad = load;
  19055. _this._delayedOnError = onError;
  19056. return _this;
  19057. }
  19058. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19059. if (!_this._texture) {
  19060. if (!scene.useDelayedTextureLoading) {
  19061. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19062. if (deleteBuffer) {
  19063. delete _this._buffer;
  19064. }
  19065. }
  19066. else {
  19067. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19068. _this._delayedOnLoad = load;
  19069. _this._delayedOnError = onError;
  19070. }
  19071. }
  19072. else {
  19073. if (_this._texture.isReady) {
  19074. BABYLON.Tools.SetImmediate(function () { return load(); });
  19075. }
  19076. else {
  19077. _this._texture.onLoadedCallbacks.push(load);
  19078. }
  19079. }
  19080. return _this;
  19081. }
  19082. Object.defineProperty(Texture.prototype, "noMipmap", {
  19083. get: function () {
  19084. return this._noMipmap;
  19085. },
  19086. enumerable: true,
  19087. configurable: true
  19088. });
  19089. Object.defineProperty(Texture.prototype, "isBlocking", {
  19090. get: function () {
  19091. return this._isBlocking;
  19092. },
  19093. set: function (value) {
  19094. this._isBlocking = value;
  19095. },
  19096. enumerable: true,
  19097. configurable: true
  19098. });
  19099. Texture.prototype.updateURL = function (url) {
  19100. this.url = url;
  19101. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19102. this.delayLoad();
  19103. };
  19104. Texture.prototype.delayLoad = function () {
  19105. var _this = this;
  19106. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19107. return;
  19108. }
  19109. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19110. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19111. if (!this._texture) {
  19112. 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);
  19113. if (this._deleteBuffer) {
  19114. delete this._buffer;
  19115. }
  19116. }
  19117. else {
  19118. if (this._texture.isReady) {
  19119. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19120. }
  19121. else {
  19122. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19123. }
  19124. }
  19125. };
  19126. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19127. if (!this._texture) {
  19128. return;
  19129. }
  19130. this._samplingMode = samplingMode;
  19131. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19132. };
  19133. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19134. x *= this.uScale;
  19135. y *= this.vScale;
  19136. x -= 0.5 * this.uScale;
  19137. y -= 0.5 * this.vScale;
  19138. z -= 0.5;
  19139. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19140. t.x += 0.5 * this.uScale + this.uOffset;
  19141. t.y += 0.5 * this.vScale + this.vOffset;
  19142. t.z += 0.5;
  19143. };
  19144. Texture.prototype.getTextureMatrix = function () {
  19145. if (this.uOffset === this._cachedUOffset &&
  19146. this.vOffset === this._cachedVOffset &&
  19147. this.uScale === this._cachedUScale &&
  19148. this.vScale === this._cachedVScale &&
  19149. this.uAng === this._cachedUAng &&
  19150. this.vAng === this._cachedVAng &&
  19151. this.wAng === this._cachedWAng) {
  19152. return this._cachedTextureMatrix;
  19153. }
  19154. this._cachedUOffset = this.uOffset;
  19155. this._cachedVOffset = this.vOffset;
  19156. this._cachedUScale = this.uScale;
  19157. this._cachedVScale = this.vScale;
  19158. this._cachedUAng = this.uAng;
  19159. this._cachedVAng = this.vAng;
  19160. this._cachedWAng = this.wAng;
  19161. if (!this._cachedTextureMatrix) {
  19162. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19163. this._rowGenerationMatrix = new BABYLON.Matrix();
  19164. this._t0 = BABYLON.Vector3.Zero();
  19165. this._t1 = BABYLON.Vector3.Zero();
  19166. this._t2 = BABYLON.Vector3.Zero();
  19167. }
  19168. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19169. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19170. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19171. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19172. this._t1.subtractInPlace(this._t0);
  19173. this._t2.subtractInPlace(this._t0);
  19174. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19175. this._cachedTextureMatrix.m[0] = this._t1.x;
  19176. this._cachedTextureMatrix.m[1] = this._t1.y;
  19177. this._cachedTextureMatrix.m[2] = this._t1.z;
  19178. this._cachedTextureMatrix.m[4] = this._t2.x;
  19179. this._cachedTextureMatrix.m[5] = this._t2.y;
  19180. this._cachedTextureMatrix.m[6] = this._t2.z;
  19181. this._cachedTextureMatrix.m[8] = this._t0.x;
  19182. this._cachedTextureMatrix.m[9] = this._t0.y;
  19183. this._cachedTextureMatrix.m[10] = this._t0.z;
  19184. return this._cachedTextureMatrix;
  19185. };
  19186. Texture.prototype.getReflectionTextureMatrix = function () {
  19187. if (this.uOffset === this._cachedUOffset &&
  19188. this.vOffset === this._cachedVOffset &&
  19189. this.uScale === this._cachedUScale &&
  19190. this.vScale === this._cachedVScale &&
  19191. this.coordinatesMode === this._cachedCoordinatesMode) {
  19192. return this._cachedTextureMatrix;
  19193. }
  19194. if (!this._cachedTextureMatrix) {
  19195. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19196. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19197. }
  19198. this._cachedCoordinatesMode = this.coordinatesMode;
  19199. switch (this.coordinatesMode) {
  19200. case Texture.PLANAR_MODE:
  19201. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19202. this._cachedTextureMatrix[0] = this.uScale;
  19203. this._cachedTextureMatrix[5] = this.vScale;
  19204. this._cachedTextureMatrix[12] = this.uOffset;
  19205. this._cachedTextureMatrix[13] = this.vOffset;
  19206. break;
  19207. case Texture.PROJECTION_MODE:
  19208. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19209. this._projectionModeMatrix.m[0] = 0.5;
  19210. this._projectionModeMatrix.m[5] = -0.5;
  19211. this._projectionModeMatrix.m[10] = 0.0;
  19212. this._projectionModeMatrix.m[12] = 0.5;
  19213. this._projectionModeMatrix.m[13] = 0.5;
  19214. this._projectionModeMatrix.m[14] = 1.0;
  19215. this._projectionModeMatrix.m[15] = 1.0;
  19216. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19217. break;
  19218. default:
  19219. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19220. break;
  19221. }
  19222. return this._cachedTextureMatrix;
  19223. };
  19224. Texture.prototype.clone = function () {
  19225. var _this = this;
  19226. return BABYLON.SerializationHelper.Clone(function () {
  19227. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19228. }, this);
  19229. };
  19230. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19231. get: function () {
  19232. if (!this._onLoadObservarble) {
  19233. this._onLoadObservarble = new BABYLON.Observable();
  19234. }
  19235. return this._onLoadObservarble;
  19236. },
  19237. enumerable: true,
  19238. configurable: true
  19239. });
  19240. // Statics
  19241. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19242. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19243. if (onLoad === void 0) { onLoad = null; }
  19244. if (onError === void 0) { onError = null; }
  19245. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19246. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19247. };
  19248. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19249. if (parsedTexture.customType) {
  19250. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19251. // Update Sampling Mode
  19252. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19253. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19254. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19255. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19256. }
  19257. }
  19258. return parsedCustomTexture;
  19259. }
  19260. if (parsedTexture.isCube) {
  19261. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19262. }
  19263. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19264. return null;
  19265. }
  19266. var texture = BABYLON.SerializationHelper.Parse(function () {
  19267. if (parsedTexture.mirrorPlane) {
  19268. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19269. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19270. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19271. return mirrorTexture;
  19272. }
  19273. else if (parsedTexture.isRenderTarget) {
  19274. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19275. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19276. return renderTargetTexture;
  19277. }
  19278. else {
  19279. var texture;
  19280. if (parsedTexture.base64String) {
  19281. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19282. }
  19283. else {
  19284. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19285. }
  19286. return texture;
  19287. }
  19288. }, parsedTexture, scene);
  19289. // Update Sampling Mode
  19290. if (parsedTexture.samplingMode) {
  19291. var sampling = parsedTexture.samplingMode;
  19292. if (texture._samplingMode !== sampling) {
  19293. texture.updateSamplingMode(sampling);
  19294. }
  19295. }
  19296. // Animations
  19297. if (parsedTexture.animations) {
  19298. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19299. var parsedAnimation = parsedTexture.animations[animationIndex];
  19300. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19301. }
  19302. }
  19303. return texture;
  19304. };
  19305. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19306. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19307. if (noMipmap === void 0) { noMipmap = false; }
  19308. if (invertY === void 0) { invertY = true; }
  19309. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19310. if (onLoad === void 0) { onLoad = null; }
  19311. if (onError === void 0) { onError = null; }
  19312. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19313. if (name.substr(0, 5) !== "data:") {
  19314. name = "data:" + name;
  19315. }
  19316. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19317. };
  19318. return Texture;
  19319. }(BABYLON.BaseTexture));
  19320. // Constants
  19321. Texture.NEAREST_SAMPLINGMODE = 1;
  19322. Texture.BILINEAR_SAMPLINGMODE = 2;
  19323. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19324. Texture.EXPLICIT_MODE = 0;
  19325. Texture.SPHERICAL_MODE = 1;
  19326. Texture.PLANAR_MODE = 2;
  19327. Texture.CUBIC_MODE = 3;
  19328. Texture.PROJECTION_MODE = 4;
  19329. Texture.SKYBOX_MODE = 5;
  19330. Texture.INVCUBIC_MODE = 6;
  19331. Texture.EQUIRECTANGULAR_MODE = 7;
  19332. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19333. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19334. Texture.CLAMP_ADDRESSMODE = 0;
  19335. Texture.WRAP_ADDRESSMODE = 1;
  19336. Texture.MIRROR_ADDRESSMODE = 2;
  19337. __decorate([
  19338. BABYLON.serialize()
  19339. ], Texture.prototype, "url", void 0);
  19340. __decorate([
  19341. BABYLON.serialize()
  19342. ], Texture.prototype, "uOffset", void 0);
  19343. __decorate([
  19344. BABYLON.serialize()
  19345. ], Texture.prototype, "vOffset", void 0);
  19346. __decorate([
  19347. BABYLON.serialize()
  19348. ], Texture.prototype, "uScale", void 0);
  19349. __decorate([
  19350. BABYLON.serialize()
  19351. ], Texture.prototype, "vScale", void 0);
  19352. __decorate([
  19353. BABYLON.serialize()
  19354. ], Texture.prototype, "uAng", void 0);
  19355. __decorate([
  19356. BABYLON.serialize()
  19357. ], Texture.prototype, "vAng", void 0);
  19358. __decorate([
  19359. BABYLON.serialize()
  19360. ], Texture.prototype, "wAng", void 0);
  19361. __decorate([
  19362. BABYLON.serialize()
  19363. ], Texture.prototype, "isBlocking", null);
  19364. BABYLON.Texture = Texture;
  19365. })(BABYLON || (BABYLON = {}));
  19366. //# sourceMappingURL=babylon.texture.js.map
  19367. var BABYLON;
  19368. (function (BABYLON) {
  19369. var _InstancesBatch = (function () {
  19370. function _InstancesBatch() {
  19371. this.mustReturn = false;
  19372. this.visibleInstances = new Array();
  19373. this.renderSelf = new Array();
  19374. }
  19375. return _InstancesBatch;
  19376. }());
  19377. BABYLON._InstancesBatch = _InstancesBatch;
  19378. var Mesh = (function (_super) {
  19379. __extends(Mesh, _super);
  19380. /**
  19381. * @constructor
  19382. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19383. * @param {Scene} scene The scene to add this mesh to.
  19384. * @param {Node} parent The parent of this mesh, if it has one
  19385. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19386. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19387. * When false, achieved by calling a clone(), also passing False.
  19388. * This will make creation of children, recursive.
  19389. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19390. */
  19391. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19392. if (parent === void 0) { parent = null; }
  19393. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19394. var _this = _super.call(this, name, scene) || this;
  19395. // Events
  19396. /**
  19397. * An event triggered before rendering the mesh
  19398. * @type {BABYLON.Observable}
  19399. */
  19400. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19401. /**
  19402. * An event triggered after rendering the mesh
  19403. * @type {BABYLON.Observable}
  19404. */
  19405. _this.onAfterRenderObservable = new BABYLON.Observable();
  19406. /**
  19407. * An event triggered before drawing the mesh
  19408. * @type {BABYLON.Observable}
  19409. */
  19410. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19411. // Members
  19412. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19413. _this.instances = new Array();
  19414. _this._LODLevels = new Array();
  19415. _this._visibleInstances = {};
  19416. _this._renderIdForInstances = new Array();
  19417. _this._batchCache = new _InstancesBatch();
  19418. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19419. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19420. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19421. // Will be used to save a source mesh reference, If any
  19422. _this._source = null;
  19423. if (source) {
  19424. // Source mesh
  19425. _this._source = source;
  19426. // Geometry
  19427. if (source._geometry) {
  19428. source._geometry.applyToMesh(_this);
  19429. }
  19430. // Deep copy
  19431. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19432. // Parent
  19433. _this.parent = source.parent;
  19434. // Pivot
  19435. _this.setPivotMatrix(source.getPivotMatrix());
  19436. _this.id = name + "." + source.id;
  19437. // Material
  19438. _this.material = source.material;
  19439. var index;
  19440. if (!doNotCloneChildren) {
  19441. // Children
  19442. for (index = 0; index < scene.meshes.length; index++) {
  19443. var mesh = scene.meshes[index];
  19444. if (mesh.parent === source) {
  19445. // doNotCloneChildren is always going to be False
  19446. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19447. }
  19448. }
  19449. }
  19450. // Physics clone
  19451. var physicsEngine = _this.getScene().getPhysicsEngine();
  19452. if (clonePhysicsImpostor && physicsEngine) {
  19453. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19454. if (impostor) {
  19455. _this.physicsImpostor = impostor.clone(_this);
  19456. }
  19457. }
  19458. // Particles
  19459. for (index = 0; index < scene.particleSystems.length; index++) {
  19460. var system = scene.particleSystems[index];
  19461. if (system.emitter === source) {
  19462. system.clone(system.name, _this);
  19463. }
  19464. }
  19465. _this.computeWorldMatrix(true);
  19466. }
  19467. // Parent
  19468. if (parent !== null) {
  19469. _this.parent = parent;
  19470. }
  19471. return _this;
  19472. }
  19473. Object.defineProperty(Mesh, "FRONTSIDE", {
  19474. /**
  19475. * Mesh side orientation : usually the external or front surface
  19476. */
  19477. get: function () {
  19478. return Mesh._FRONTSIDE;
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. Object.defineProperty(Mesh, "BACKSIDE", {
  19484. /**
  19485. * Mesh side orientation : usually the internal or back surface
  19486. */
  19487. get: function () {
  19488. return Mesh._BACKSIDE;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19494. /**
  19495. * Mesh side orientation : both internal and external or front and back surfaces
  19496. */
  19497. get: function () {
  19498. return Mesh._DOUBLESIDE;
  19499. },
  19500. enumerable: true,
  19501. configurable: true
  19502. });
  19503. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19504. /**
  19505. * Mesh side orientation : by default, `FRONTSIDE`
  19506. */
  19507. get: function () {
  19508. return Mesh._DEFAULTSIDE;
  19509. },
  19510. enumerable: true,
  19511. configurable: true
  19512. });
  19513. Object.defineProperty(Mesh, "NO_CAP", {
  19514. /**
  19515. * Mesh cap setting : no cap
  19516. */
  19517. get: function () {
  19518. return Mesh._NO_CAP;
  19519. },
  19520. enumerable: true,
  19521. configurable: true
  19522. });
  19523. Object.defineProperty(Mesh, "CAP_START", {
  19524. /**
  19525. * Mesh cap setting : one cap at the beginning of the mesh
  19526. */
  19527. get: function () {
  19528. return Mesh._CAP_START;
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(Mesh, "CAP_END", {
  19534. /**
  19535. * Mesh cap setting : one cap at the end of the mesh
  19536. */
  19537. get: function () {
  19538. return Mesh._CAP_END;
  19539. },
  19540. enumerable: true,
  19541. configurable: true
  19542. });
  19543. Object.defineProperty(Mesh, "CAP_ALL", {
  19544. /**
  19545. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19546. */
  19547. get: function () {
  19548. return Mesh._CAP_ALL;
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19554. set: function (callback) {
  19555. if (this._onBeforeDrawObserver) {
  19556. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19557. }
  19558. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19564. get: function () {
  19565. return this._morphTargetManager;
  19566. },
  19567. set: function (value) {
  19568. if (this._morphTargetManager === value) {
  19569. return;
  19570. }
  19571. this._morphTargetManager = value;
  19572. this._syncGeometryWithMorphTargetManager();
  19573. },
  19574. enumerable: true,
  19575. configurable: true
  19576. });
  19577. Object.defineProperty(Mesh.prototype, "source", {
  19578. get: function () {
  19579. return this._source;
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. // Methods
  19585. /**
  19586. * Returns the string "Mesh".
  19587. */
  19588. Mesh.prototype.getClassName = function () {
  19589. return "Mesh";
  19590. };
  19591. /**
  19592. * Returns a string.
  19593. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19594. */
  19595. Mesh.prototype.toString = function (fullDetails) {
  19596. var ret = _super.prototype.toString.call(this, fullDetails);
  19597. ret += ", n vertices: " + this.getTotalVertices();
  19598. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19599. if (this.animations) {
  19600. for (var i = 0; i < this.animations.length; i++) {
  19601. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19602. }
  19603. }
  19604. if (fullDetails) {
  19605. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19606. }
  19607. return ret;
  19608. };
  19609. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19610. /**
  19611. * True if the mesh has some Levels Of Details (LOD).
  19612. * Returns a boolean.
  19613. */
  19614. get: function () {
  19615. return this._LODLevels.length > 0;
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Mesh.prototype._sortLODLevels = function () {
  19621. this._LODLevels.sort(function (a, b) {
  19622. if (a.distance < b.distance) {
  19623. return 1;
  19624. }
  19625. if (a.distance > b.distance) {
  19626. return -1;
  19627. }
  19628. return 0;
  19629. });
  19630. };
  19631. /**
  19632. * Add a mesh as LOD level triggered at the given distance.
  19633. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19634. * @param {number} distance The distance from the center of the object to show this level
  19635. * @param {Mesh} mesh The mesh to be added as LOD level
  19636. * @return {Mesh} This mesh (for chaining)
  19637. */
  19638. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19639. if (mesh && mesh._masterMesh) {
  19640. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19641. return this;
  19642. }
  19643. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19644. this._LODLevels.push(level);
  19645. if (mesh) {
  19646. mesh._masterMesh = this;
  19647. }
  19648. this._sortLODLevels();
  19649. return this;
  19650. };
  19651. /**
  19652. * Returns the LOD level mesh at the passed distance or null if not found.
  19653. * It is related to the method `addLODLevel(distance, mesh)`.
  19654. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19655. * Returns an object Mesh or `null`.
  19656. */
  19657. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19658. for (var index = 0; index < this._LODLevels.length; index++) {
  19659. var level = this._LODLevels[index];
  19660. if (level.distance === distance) {
  19661. return level.mesh;
  19662. }
  19663. }
  19664. return null;
  19665. };
  19666. /**
  19667. * Remove a mesh from the LOD array
  19668. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19669. * @param {Mesh} mesh The mesh to be removed.
  19670. * @return {Mesh} This mesh (for chaining)
  19671. */
  19672. Mesh.prototype.removeLODLevel = function (mesh) {
  19673. for (var index = 0; index < this._LODLevels.length; index++) {
  19674. if (this._LODLevels[index].mesh === mesh) {
  19675. this._LODLevels.splice(index, 1);
  19676. if (mesh) {
  19677. mesh._masterMesh = null;
  19678. }
  19679. }
  19680. }
  19681. this._sortLODLevels();
  19682. return this;
  19683. };
  19684. /**
  19685. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19686. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19687. */
  19688. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19689. if (!this._LODLevels || this._LODLevels.length === 0) {
  19690. return this;
  19691. }
  19692. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19693. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19694. if (this.onLODLevelSelection) {
  19695. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19696. }
  19697. return this;
  19698. }
  19699. for (var index = 0; index < this._LODLevels.length; index++) {
  19700. var level = this._LODLevels[index];
  19701. if (level.distance < distanceToCamera) {
  19702. if (level.mesh) {
  19703. level.mesh._preActivate();
  19704. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19705. }
  19706. if (this.onLODLevelSelection) {
  19707. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19708. }
  19709. return level.mesh;
  19710. }
  19711. }
  19712. if (this.onLODLevelSelection) {
  19713. this.onLODLevelSelection(distanceToCamera, this, this);
  19714. }
  19715. return this;
  19716. };
  19717. Object.defineProperty(Mesh.prototype, "geometry", {
  19718. /**
  19719. * Returns the mesh internal Geometry object.
  19720. */
  19721. get: function () {
  19722. return this._geometry;
  19723. },
  19724. enumerable: true,
  19725. configurable: true
  19726. });
  19727. /**
  19728. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19729. */
  19730. Mesh.prototype.getTotalVertices = function () {
  19731. if (!this._geometry) {
  19732. return 0;
  19733. }
  19734. return this._geometry.getTotalVertices();
  19735. };
  19736. /**
  19737. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19738. * 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.
  19739. * You can force the copy with forceCopy === true
  19740. * Returns null if the mesh has no geometry or no vertex buffer.
  19741. * Possible `kind` values :
  19742. * - BABYLON.VertexBuffer.PositionKind
  19743. * - BABYLON.VertexBuffer.UVKind
  19744. * - BABYLON.VertexBuffer.UV2Kind
  19745. * - BABYLON.VertexBuffer.UV3Kind
  19746. * - BABYLON.VertexBuffer.UV4Kind
  19747. * - BABYLON.VertexBuffer.UV5Kind
  19748. * - BABYLON.VertexBuffer.UV6Kind
  19749. * - BABYLON.VertexBuffer.ColorKind
  19750. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19751. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19752. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19753. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19754. */
  19755. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19756. if (!this._geometry) {
  19757. return null;
  19758. }
  19759. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19760. };
  19761. /**
  19762. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19763. * Returns `undefined` if the mesh has no geometry.
  19764. * Possible `kind` values :
  19765. * - BABYLON.VertexBuffer.PositionKind
  19766. * - BABYLON.VertexBuffer.UVKind
  19767. * - BABYLON.VertexBuffer.UV2Kind
  19768. * - BABYLON.VertexBuffer.UV3Kind
  19769. * - BABYLON.VertexBuffer.UV4Kind
  19770. * - BABYLON.VertexBuffer.UV5Kind
  19771. * - BABYLON.VertexBuffer.UV6Kind
  19772. * - BABYLON.VertexBuffer.ColorKind
  19773. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19774. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19775. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19776. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19777. */
  19778. Mesh.prototype.getVertexBuffer = function (kind) {
  19779. if (!this._geometry) {
  19780. return undefined;
  19781. }
  19782. return this._geometry.getVertexBuffer(kind);
  19783. };
  19784. /**
  19785. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19786. * Possible `kind` values :
  19787. * - BABYLON.VertexBuffer.PositionKind
  19788. * - BABYLON.VertexBuffer.UVKind
  19789. * - BABYLON.VertexBuffer.UV2Kind
  19790. * - BABYLON.VertexBuffer.UV3Kind
  19791. * - BABYLON.VertexBuffer.UV4Kind
  19792. * - BABYLON.VertexBuffer.UV5Kind
  19793. * - BABYLON.VertexBuffer.UV6Kind
  19794. * - BABYLON.VertexBuffer.ColorKind
  19795. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19796. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19797. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19798. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19799. */
  19800. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19801. if (!this._geometry) {
  19802. if (this._delayInfo) {
  19803. return this._delayInfo.indexOf(kind) !== -1;
  19804. }
  19805. return false;
  19806. }
  19807. return this._geometry.isVerticesDataPresent(kind);
  19808. };
  19809. /**
  19810. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19811. * Possible `kind` values :
  19812. * - BABYLON.VertexBuffer.PositionKind
  19813. * - BABYLON.VertexBuffer.UVKind
  19814. * - BABYLON.VertexBuffer.UV2Kind
  19815. * - BABYLON.VertexBuffer.UV3Kind
  19816. * - BABYLON.VertexBuffer.UV4Kind
  19817. * - BABYLON.VertexBuffer.UV5Kind
  19818. * - BABYLON.VertexBuffer.UV6Kind
  19819. * - BABYLON.VertexBuffer.ColorKind
  19820. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19821. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19822. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19823. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19824. */
  19825. Mesh.prototype.getVerticesDataKinds = function () {
  19826. if (!this._geometry) {
  19827. var result = [];
  19828. if (this._delayInfo) {
  19829. this._delayInfo.forEach(function (kind, index, array) {
  19830. result.push(kind);
  19831. });
  19832. }
  19833. return result;
  19834. }
  19835. return this._geometry.getVerticesDataKinds();
  19836. };
  19837. /**
  19838. * Returns a positive integer : the total number of indices in this mesh geometry.
  19839. * Returns zero if the mesh has no geometry.
  19840. */
  19841. Mesh.prototype.getTotalIndices = function () {
  19842. if (!this._geometry) {
  19843. return 0;
  19844. }
  19845. return this._geometry.getTotalIndices();
  19846. };
  19847. /**
  19848. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19849. * 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.
  19850. * Returns an empty array if the mesh has no geometry.
  19851. */
  19852. Mesh.prototype.getIndices = function (copyWhenShared) {
  19853. if (!this._geometry) {
  19854. return [];
  19855. }
  19856. return this._geometry.getIndices(copyWhenShared);
  19857. };
  19858. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19859. get: function () {
  19860. return this._masterMesh !== null && this._masterMesh !== undefined;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. /**
  19866. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19867. */
  19868. Mesh.prototype.isReady = function () {
  19869. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19870. return false;
  19871. }
  19872. return _super.prototype.isReady.call(this);
  19873. };
  19874. /**
  19875. * Boolean : true if the mesh has been disposed.
  19876. */
  19877. Mesh.prototype.isDisposed = function () {
  19878. return this._isDisposed;
  19879. };
  19880. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19881. get: function () {
  19882. return this._sideOrientation;
  19883. },
  19884. /**
  19885. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19886. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19887. */
  19888. set: function (sideO) {
  19889. this._sideOrientation = sideO;
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19895. /**
  19896. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19897. * This property is pertinent only for updatable parametric shapes.
  19898. */
  19899. get: function () {
  19900. return this._areNormalsFrozen;
  19901. },
  19902. enumerable: true,
  19903. configurable: true
  19904. });
  19905. /**
  19906. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19907. * It has no effect at all on other shapes.
  19908. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19909. * Returns the Mesh.
  19910. */
  19911. Mesh.prototype.freezeNormals = function () {
  19912. this._areNormalsFrozen = true;
  19913. return this;
  19914. };
  19915. /**
  19916. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19917. * It has no effect at all on other shapes.
  19918. * It reactivates the mesh normals computation if it was previously frozen.
  19919. * Returns the Mesh.
  19920. */
  19921. Mesh.prototype.unfreezeNormals = function () {
  19922. this._areNormalsFrozen = false;
  19923. return this;
  19924. };
  19925. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19926. /**
  19927. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19928. */
  19929. set: function (count) {
  19930. this._overridenInstanceCount = count;
  19931. },
  19932. enumerable: true,
  19933. configurable: true
  19934. });
  19935. // Methods
  19936. Mesh.prototype._preActivate = function () {
  19937. var sceneRenderId = this.getScene().getRenderId();
  19938. if (this._preActivateId === sceneRenderId) {
  19939. return this;
  19940. }
  19941. this._preActivateId = sceneRenderId;
  19942. this._visibleInstances = null;
  19943. return this;
  19944. };
  19945. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19946. if (this._visibleInstances) {
  19947. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19948. }
  19949. return this;
  19950. };
  19951. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19952. if (!this._visibleInstances) {
  19953. this._visibleInstances = {};
  19954. this._visibleInstances.defaultRenderId = renderId;
  19955. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19956. }
  19957. if (!this._visibleInstances[renderId]) {
  19958. this._visibleInstances[renderId] = new Array();
  19959. }
  19960. this._visibleInstances[renderId].push(instance);
  19961. return this;
  19962. };
  19963. /**
  19964. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19965. * This means the mesh underlying bounding box and sphere are recomputed.
  19966. * Returns the Mesh.
  19967. */
  19968. Mesh.prototype.refreshBoundingInfo = function () {
  19969. if (this._boundingInfo.isLocked) {
  19970. return;
  19971. }
  19972. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19973. if (data) {
  19974. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19975. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19976. }
  19977. if (this.subMeshes) {
  19978. for (var index = 0; index < this.subMeshes.length; index++) {
  19979. this.subMeshes[index].refreshBoundingInfo();
  19980. }
  19981. }
  19982. this._updateBoundingInfo();
  19983. return this;
  19984. };
  19985. Mesh.prototype._createGlobalSubMesh = function () {
  19986. var totalVertices = this.getTotalVertices();
  19987. if (!totalVertices || !this.getIndices()) {
  19988. return null;
  19989. }
  19990. this.releaseSubMeshes();
  19991. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19992. };
  19993. Mesh.prototype.subdivide = function (count) {
  19994. if (count < 1) {
  19995. return;
  19996. }
  19997. var totalIndices = this.getTotalIndices();
  19998. var subdivisionSize = (totalIndices / count) | 0;
  19999. var offset = 0;
  20000. // Ensure that subdivisionSize is a multiple of 3
  20001. while (subdivisionSize % 3 !== 0) {
  20002. subdivisionSize++;
  20003. }
  20004. this.releaseSubMeshes();
  20005. for (var index = 0; index < count; index++) {
  20006. if (offset >= totalIndices) {
  20007. break;
  20008. }
  20009. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20010. offset += subdivisionSize;
  20011. }
  20012. this.synchronizeInstances();
  20013. };
  20014. /**
  20015. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20016. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20017. * The `data` are either a numeric array either a Float32Array.
  20018. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20019. * 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).
  20020. * Note that a new underlying VertexBuffer object is created each call.
  20021. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20022. *
  20023. * Possible `kind` values :
  20024. * - BABYLON.VertexBuffer.PositionKind
  20025. * - BABYLON.VertexBuffer.UVKind
  20026. * - BABYLON.VertexBuffer.UV2Kind
  20027. * - BABYLON.VertexBuffer.UV3Kind
  20028. * - BABYLON.VertexBuffer.UV4Kind
  20029. * - BABYLON.VertexBuffer.UV5Kind
  20030. * - BABYLON.VertexBuffer.UV6Kind
  20031. * - BABYLON.VertexBuffer.ColorKind
  20032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20036. *
  20037. * Returns the Mesh.
  20038. */
  20039. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20040. if (!this._geometry) {
  20041. var vertexData = new BABYLON.VertexData();
  20042. vertexData.set(data, kind);
  20043. var scene = this.getScene();
  20044. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20045. }
  20046. else {
  20047. this._geometry.setVerticesData(kind, data, updatable, stride);
  20048. }
  20049. return this;
  20050. };
  20051. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20052. if (updatable === void 0) { updatable = true; }
  20053. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20054. return;
  20055. }
  20056. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20057. };
  20058. /**
  20059. * Sets the mesh VertexBuffer.
  20060. * Returns the Mesh.
  20061. */
  20062. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20063. if (!this._geometry) {
  20064. var scene = this.getScene();
  20065. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20066. }
  20067. this._geometry.setVerticesBuffer(buffer);
  20068. return this;
  20069. };
  20070. /**
  20071. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20072. * If the mesh has no geometry, it is simply returned as it is.
  20073. * The `data` are either a numeric array either a Float32Array.
  20074. * No new underlying VertexBuffer object is created.
  20075. * 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.
  20076. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20077. *
  20078. * Possible `kind` values :
  20079. * - BABYLON.VertexBuffer.PositionKind
  20080. * - BABYLON.VertexBuffer.UVKind
  20081. * - BABYLON.VertexBuffer.UV2Kind
  20082. * - BABYLON.VertexBuffer.UV3Kind
  20083. * - BABYLON.VertexBuffer.UV4Kind
  20084. * - BABYLON.VertexBuffer.UV5Kind
  20085. * - BABYLON.VertexBuffer.UV6Kind
  20086. * - BABYLON.VertexBuffer.ColorKind
  20087. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20088. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20089. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20090. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20091. *
  20092. * Returns the Mesh.
  20093. */
  20094. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20095. if (!this._geometry) {
  20096. return;
  20097. }
  20098. if (!makeItUnique) {
  20099. this._geometry.updateVerticesData(kind, data, updateExtends);
  20100. }
  20101. else {
  20102. this.makeGeometryUnique();
  20103. this.updateVerticesData(kind, data, updateExtends, false);
  20104. }
  20105. return this;
  20106. };
  20107. /**
  20108. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20109. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20110. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20111. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20112. * Returns the Mesh.
  20113. */
  20114. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20115. if (computeNormals === void 0) { computeNormals = true; }
  20116. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20117. positionFunction(positions);
  20118. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20119. if (computeNormals) {
  20120. var indices = this.getIndices();
  20121. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20122. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20123. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20124. }
  20125. return this;
  20126. };
  20127. /**
  20128. * Creates a un-shared specific occurence of the geometry for the mesh.
  20129. * Returns the Mesh.
  20130. */
  20131. Mesh.prototype.makeGeometryUnique = function () {
  20132. if (!this._geometry) {
  20133. return;
  20134. }
  20135. var oldGeometry = this._geometry;
  20136. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20137. oldGeometry.releaseForMesh(this, true);
  20138. geometry.applyToMesh(this);
  20139. return this;
  20140. };
  20141. /**
  20142. * Sets the mesh indices.
  20143. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20144. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20145. * This method creates a new index buffer each call.
  20146. * Returns the Mesh.
  20147. */
  20148. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20149. if (!this._geometry) {
  20150. var vertexData = new BABYLON.VertexData();
  20151. vertexData.indices = indices;
  20152. var scene = this.getScene();
  20153. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20154. }
  20155. else {
  20156. this._geometry.setIndices(indices, totalVertices);
  20157. }
  20158. return this;
  20159. };
  20160. /**
  20161. * Invert the geometry to move from a right handed system to a left handed one.
  20162. * Returns the Mesh.
  20163. */
  20164. Mesh.prototype.toLeftHanded = function () {
  20165. if (!this._geometry) {
  20166. return;
  20167. }
  20168. this._geometry.toLeftHanded();
  20169. return this;
  20170. };
  20171. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20172. var engine = this.getScene().getEngine();
  20173. // Wireframe
  20174. var indexToBind;
  20175. if (this._unIndexed) {
  20176. indexToBind = null;
  20177. }
  20178. else {
  20179. switch (fillMode) {
  20180. case BABYLON.Material.PointFillMode:
  20181. indexToBind = null;
  20182. break;
  20183. case BABYLON.Material.WireFrameFillMode:
  20184. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20185. break;
  20186. default:
  20187. case BABYLON.Material.TriangleFillMode:
  20188. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20189. break;
  20190. }
  20191. }
  20192. // VBOs
  20193. this._geometry._bind(effect, indexToBind);
  20194. return this;
  20195. };
  20196. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20197. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20198. return this;
  20199. }
  20200. this.onBeforeDrawObservable.notifyObservers(this);
  20201. var engine = this.getScene().getEngine();
  20202. // Draw order
  20203. switch (fillMode) {
  20204. case BABYLON.Material.PointFillMode:
  20205. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20206. break;
  20207. case BABYLON.Material.WireFrameFillMode:
  20208. if (this._unIndexed) {
  20209. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20210. }
  20211. else {
  20212. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20213. }
  20214. break;
  20215. default:
  20216. if (this._unIndexed) {
  20217. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20218. }
  20219. else {
  20220. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20221. }
  20222. }
  20223. return this;
  20224. };
  20225. /**
  20226. * Registers for this mesh a javascript function called just before the rendering process.
  20227. * This function is passed the current mesh.
  20228. * Return the Mesh.
  20229. */
  20230. Mesh.prototype.registerBeforeRender = function (func) {
  20231. this.onBeforeRenderObservable.add(func);
  20232. return this;
  20233. };
  20234. /**
  20235. * Disposes a previously registered javascript function called before the rendering.
  20236. * This function is passed the current mesh.
  20237. * Returns the Mesh.
  20238. */
  20239. Mesh.prototype.unregisterBeforeRender = function (func) {
  20240. this.onBeforeRenderObservable.removeCallback(func);
  20241. return this;
  20242. };
  20243. /**
  20244. * Registers for this mesh a javascript function called just after the rendering is complete.
  20245. * This function is passed the current mesh.
  20246. * Returns the Mesh.
  20247. */
  20248. Mesh.prototype.registerAfterRender = function (func) {
  20249. this.onAfterRenderObservable.add(func);
  20250. return this;
  20251. };
  20252. /**
  20253. * Disposes a previously registered javascript function called after the rendering.
  20254. * This function is passed the current mesh.
  20255. * Return the Mesh.
  20256. */
  20257. Mesh.prototype.unregisterAfterRender = function (func) {
  20258. this.onAfterRenderObservable.removeCallback(func);
  20259. return this;
  20260. };
  20261. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20262. var scene = this.getScene();
  20263. this._batchCache.mustReturn = false;
  20264. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20265. this._batchCache.visibleInstances[subMeshId] = null;
  20266. if (this._visibleInstances) {
  20267. var currentRenderId = scene.getRenderId();
  20268. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20269. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20270. var selfRenderId = this._renderId;
  20271. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20272. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20273. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20274. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20275. }
  20276. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20277. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20278. this._batchCache.mustReturn = true;
  20279. return this._batchCache;
  20280. }
  20281. if (currentRenderId !== selfRenderId) {
  20282. this._batchCache.renderSelf[subMeshId] = false;
  20283. }
  20284. }
  20285. this._renderIdForInstances[subMeshId] = currentRenderId;
  20286. }
  20287. return this._batchCache;
  20288. };
  20289. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20290. var visibleInstances = batch.visibleInstances[subMesh._id];
  20291. var matricesCount = visibleInstances.length + 1;
  20292. var bufferSize = matricesCount * 16 * 4;
  20293. var currentInstancesBufferSize = this._instancesBufferSize;
  20294. var instancesBuffer = this._instancesBuffer;
  20295. while (this._instancesBufferSize < bufferSize) {
  20296. this._instancesBufferSize *= 2;
  20297. }
  20298. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20299. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20300. }
  20301. var offset = 0;
  20302. var instancesCount = 0;
  20303. var world = this.getWorldMatrix();
  20304. if (batch.renderSelf[subMesh._id]) {
  20305. world.copyToArray(this._instancesData, offset);
  20306. offset += 16;
  20307. instancesCount++;
  20308. }
  20309. if (visibleInstances) {
  20310. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20311. var instance = visibleInstances[instanceIndex];
  20312. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20313. offset += 16;
  20314. instancesCount++;
  20315. }
  20316. }
  20317. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20318. if (instancesBuffer) {
  20319. instancesBuffer.dispose();
  20320. }
  20321. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20322. this._instancesBuffer = instancesBuffer;
  20323. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20324. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20325. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20326. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20327. }
  20328. else {
  20329. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20330. }
  20331. this.geometry._bind(effect);
  20332. this._draw(subMesh, fillMode, instancesCount);
  20333. engine.unbindInstanceAttributes();
  20334. return this;
  20335. };
  20336. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20337. var scene = this.getScene();
  20338. var engine = scene.getEngine();
  20339. if (hardwareInstancedRendering) {
  20340. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20341. }
  20342. else {
  20343. if (batch.renderSelf[subMesh._id]) {
  20344. // Draw
  20345. if (onBeforeDraw) {
  20346. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20347. }
  20348. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20349. }
  20350. if (batch.visibleInstances[subMesh._id]) {
  20351. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20352. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20353. // World
  20354. var world = instance.getWorldMatrix();
  20355. if (onBeforeDraw) {
  20356. onBeforeDraw(true, world, effectiveMaterial);
  20357. }
  20358. // Draw
  20359. this._draw(subMesh, fillMode);
  20360. }
  20361. }
  20362. }
  20363. return this;
  20364. };
  20365. /**
  20366. * Triggers the draw call for the mesh.
  20367. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20368. * Returns the Mesh.
  20369. */
  20370. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20371. var scene = this.getScene();
  20372. // Managing instances
  20373. var batch = this._getInstancesRenderList(subMesh._id);
  20374. if (batch.mustReturn) {
  20375. return this;
  20376. }
  20377. // Checking geometry state
  20378. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20379. return this;
  20380. }
  20381. var callbackIndex;
  20382. this.onBeforeRenderObservable.notifyObservers(this);
  20383. var engine = scene.getEngine();
  20384. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20385. // Material
  20386. var effectiveMaterial = subMesh.getMaterial();
  20387. if (!effectiveMaterial) {
  20388. return this;
  20389. }
  20390. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20391. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20392. return this;
  20393. }
  20394. }
  20395. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20396. return this;
  20397. }
  20398. // Alpha mode
  20399. if (enableAlphaMode) {
  20400. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20401. }
  20402. // Outline - step 1
  20403. var savedDepthWrite = engine.getDepthWrite();
  20404. if (this.renderOutline) {
  20405. engine.setDepthWrite(false);
  20406. scene.getOutlineRenderer().render(subMesh, batch);
  20407. engine.setDepthWrite(savedDepthWrite);
  20408. }
  20409. var effect;
  20410. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20411. effect = subMesh.effect;
  20412. }
  20413. else {
  20414. effect = effectiveMaterial.getEffect();
  20415. }
  20416. effectiveMaterial._preBind(effect);
  20417. // Bind
  20418. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20419. this._bind(subMesh, effect, fillMode);
  20420. var world = this.getWorldMatrix();
  20421. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20422. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20423. }
  20424. else {
  20425. effectiveMaterial.bind(world, this);
  20426. }
  20427. // Draw
  20428. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20429. // Unbind
  20430. effectiveMaterial.unbind();
  20431. // Outline - step 2
  20432. if (this.renderOutline && savedDepthWrite) {
  20433. engine.setDepthWrite(true);
  20434. engine.setColorWrite(false);
  20435. scene.getOutlineRenderer().render(subMesh, batch);
  20436. engine.setColorWrite(true);
  20437. }
  20438. // Overlay
  20439. if (this.renderOverlay) {
  20440. var currentMode = engine.getAlphaMode();
  20441. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20442. scene.getOutlineRenderer().render(subMesh, batch, true);
  20443. engine.setAlphaMode(currentMode);
  20444. }
  20445. this.onAfterRenderObservable.notifyObservers(this);
  20446. return this;
  20447. };
  20448. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20449. if (isInstance) {
  20450. effectiveMaterial.bindOnlyWorldMatrix(world);
  20451. }
  20452. return this;
  20453. };
  20454. /**
  20455. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20456. */
  20457. Mesh.prototype.getEmittedParticleSystems = function () {
  20458. var results = new Array();
  20459. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20460. var particleSystem = this.getScene().particleSystems[index];
  20461. if (particleSystem.emitter === this) {
  20462. results.push(particleSystem);
  20463. }
  20464. }
  20465. return results;
  20466. };
  20467. /**
  20468. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20469. */
  20470. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20471. var results = new Array();
  20472. var descendants = this.getDescendants();
  20473. descendants.push(this);
  20474. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20475. var particleSystem = this.getScene().particleSystems[index];
  20476. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20477. results.push(particleSystem);
  20478. }
  20479. }
  20480. return results;
  20481. };
  20482. Mesh.prototype._checkDelayState = function () {
  20483. var scene = this.getScene();
  20484. if (this._geometry) {
  20485. this._geometry.load(scene);
  20486. }
  20487. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20488. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20489. this._queueLoad(this, scene);
  20490. }
  20491. return this;
  20492. };
  20493. Mesh.prototype._queueLoad = function (mesh, scene) {
  20494. var _this = this;
  20495. scene._addPendingData(mesh);
  20496. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20497. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20498. if (data instanceof ArrayBuffer) {
  20499. _this._delayLoadingFunction(data, _this);
  20500. }
  20501. else {
  20502. _this._delayLoadingFunction(JSON.parse(data), _this);
  20503. }
  20504. _this.instances.forEach(function (instance) {
  20505. instance._syncSubMeshes();
  20506. });
  20507. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20508. scene._removePendingData(_this);
  20509. }, function () { }, scene.database, getBinaryData);
  20510. return this;
  20511. };
  20512. /**
  20513. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20514. */
  20515. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20516. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20517. return false;
  20518. }
  20519. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20520. return false;
  20521. }
  20522. this._checkDelayState();
  20523. return true;
  20524. };
  20525. /**
  20526. * Sets the mesh material by the material or multiMaterial `id` property.
  20527. * The material `id` is a string identifying the material or the multiMaterial.
  20528. * This method returns the Mesh.
  20529. */
  20530. Mesh.prototype.setMaterialByID = function (id) {
  20531. var materials = this.getScene().materials;
  20532. var index;
  20533. for (index = materials.length - 1; index > -1; index--) {
  20534. if (materials[index].id === id) {
  20535. this.material = materials[index];
  20536. return this;
  20537. }
  20538. }
  20539. // Multi
  20540. var multiMaterials = this.getScene().multiMaterials;
  20541. for (index = multiMaterials.length - 1; index > -1; index--) {
  20542. if (multiMaterials[index].id === id) {
  20543. this.material = multiMaterials[index];
  20544. return this;
  20545. }
  20546. }
  20547. return this;
  20548. };
  20549. /**
  20550. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20551. */
  20552. Mesh.prototype.getAnimatables = function () {
  20553. var results = [];
  20554. if (this.material) {
  20555. results.push(this.material);
  20556. }
  20557. if (this.skeleton) {
  20558. results.push(this.skeleton);
  20559. }
  20560. return results;
  20561. };
  20562. /**
  20563. * Modifies the mesh geometry according to the passed transformation matrix.
  20564. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20565. * The mesh normals are modified accordingly the same transformation.
  20566. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20567. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20568. * Returns the Mesh.
  20569. */
  20570. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20571. // Position
  20572. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20573. return this;
  20574. }
  20575. var submeshes = this.subMeshes.splice(0);
  20576. this._resetPointsArrayCache();
  20577. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20578. var temp = [];
  20579. var index;
  20580. for (index = 0; index < data.length; index += 3) {
  20581. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20582. }
  20583. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20584. // Normals
  20585. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20586. return this;
  20587. }
  20588. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20589. temp = [];
  20590. for (index = 0; index < data.length; index += 3) {
  20591. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20592. }
  20593. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20594. // flip faces?
  20595. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20596. this.flipFaces();
  20597. }
  20598. // Restore submeshes
  20599. this.releaseSubMeshes();
  20600. this.subMeshes = submeshes;
  20601. return this;
  20602. };
  20603. /**
  20604. * Modifies the mesh geometry according to its own current World Matrix.
  20605. * The mesh World Matrix is then reset.
  20606. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20607. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20608. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20609. * Returns the Mesh.
  20610. */
  20611. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20612. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20613. this.scaling.copyFromFloats(1, 1, 1);
  20614. this.position.copyFromFloats(0, 0, 0);
  20615. this.rotation.copyFromFloats(0, 0, 0);
  20616. //only if quaternion is already set
  20617. if (this.rotationQuaternion) {
  20618. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20619. }
  20620. this._worldMatrix = BABYLON.Matrix.Identity();
  20621. return this;
  20622. };
  20623. Object.defineProperty(Mesh.prototype, "_positions", {
  20624. // Cache
  20625. get: function () {
  20626. if (this._geometry) {
  20627. return this._geometry._positions;
  20628. }
  20629. return null;
  20630. },
  20631. enumerable: true,
  20632. configurable: true
  20633. });
  20634. Mesh.prototype._resetPointsArrayCache = function () {
  20635. if (this._geometry) {
  20636. this._geometry._resetPointsArrayCache();
  20637. }
  20638. return this;
  20639. };
  20640. Mesh.prototype._generatePointsArray = function () {
  20641. if (this._geometry) {
  20642. return this._geometry._generatePointsArray();
  20643. }
  20644. return false;
  20645. };
  20646. /**
  20647. * Returns a new Mesh object generated from the current mesh properties.
  20648. * This method must not get confused with createInstance().
  20649. * The parameter `name` is a string, the name given to the new mesh.
  20650. * The optional parameter `newParent` can be any Node object (default `null`).
  20651. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20652. * 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.
  20653. */
  20654. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20655. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20656. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20657. };
  20658. /**
  20659. * Disposes the mesh.
  20660. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20661. */
  20662. Mesh.prototype.dispose = function (doNotRecurse) {
  20663. var _this = this;
  20664. this.morphTargetManager = undefined;
  20665. if (this._geometry) {
  20666. this._geometry.releaseForMesh(this, true);
  20667. }
  20668. // Sources
  20669. var meshes = this.getScene().meshes;
  20670. meshes.forEach(function (mesh) {
  20671. if (mesh._source && mesh._source === _this) {
  20672. mesh._source = null;
  20673. }
  20674. });
  20675. this._source = null;
  20676. // Instances
  20677. if (this._instancesBuffer) {
  20678. this._instancesBuffer.dispose();
  20679. this._instancesBuffer = null;
  20680. }
  20681. while (this.instances.length) {
  20682. this.instances[0].dispose();
  20683. }
  20684. // Highlight layers.
  20685. var highlightLayers = this.getScene().highlightLayers;
  20686. for (var i = 0; i < highlightLayers.length; i++) {
  20687. var highlightLayer = highlightLayers[i];
  20688. if (highlightLayer) {
  20689. highlightLayer.removeMesh(this);
  20690. highlightLayer.removeExcludedMesh(this);
  20691. }
  20692. }
  20693. _super.prototype.dispose.call(this, doNotRecurse);
  20694. };
  20695. /**
  20696. * Modifies the mesh geometry according to a displacement map.
  20697. * 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.
  20698. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20699. * This method returns nothing.
  20700. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20701. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20702. * 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.
  20703. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20704. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20705. *
  20706. * Returns the Mesh.
  20707. */
  20708. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20709. var _this = this;
  20710. var scene = this.getScene();
  20711. var onload = function (img) {
  20712. // Getting height map data
  20713. var canvas = document.createElement("canvas");
  20714. var context = canvas.getContext("2d");
  20715. var heightMapWidth = img.width;
  20716. var heightMapHeight = img.height;
  20717. canvas.width = heightMapWidth;
  20718. canvas.height = heightMapHeight;
  20719. context.drawImage(img, 0, 0);
  20720. // Create VertexData from map data
  20721. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20722. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20723. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20724. //execute success callback, if set
  20725. if (onSuccess) {
  20726. onSuccess(_this);
  20727. }
  20728. };
  20729. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20730. return this;
  20731. };
  20732. /**
  20733. * Modifies the mesh geometry according to a displacementMap buffer.
  20734. * 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.
  20735. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20736. * This method returns nothing.
  20737. * 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.
  20738. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20739. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20740. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20741. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20742. *
  20743. * Returns the Mesh.
  20744. */
  20745. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20746. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20747. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20748. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20749. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20750. return this;
  20751. }
  20752. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20753. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20754. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20755. var position = BABYLON.Vector3.Zero();
  20756. var normal = BABYLON.Vector3.Zero();
  20757. var uv = BABYLON.Vector2.Zero();
  20758. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20759. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20760. for (var index = 0; index < positions.length; index += 3) {
  20761. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20762. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20763. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20764. // Compute height
  20765. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20766. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20767. var pos = (u + v * heightMapWidth) * 4;
  20768. var r = buffer[pos] / 255.0;
  20769. var g = buffer[pos + 1] / 255.0;
  20770. var b = buffer[pos + 2] / 255.0;
  20771. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20772. normal.normalize();
  20773. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20774. position = position.add(normal);
  20775. position.toArray(positions, index);
  20776. }
  20777. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20778. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20779. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20780. return this;
  20781. };
  20782. /**
  20783. * Modify the mesh to get a flat shading rendering.
  20784. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20785. * This method returns the Mesh.
  20786. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20787. */
  20788. Mesh.prototype.convertToFlatShadedMesh = function () {
  20789. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20790. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20791. var kinds = this.getVerticesDataKinds();
  20792. var vbs = [];
  20793. var data = [];
  20794. var newdata = [];
  20795. var updatableNormals = false;
  20796. var kindIndex;
  20797. var kind;
  20798. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20799. kind = kinds[kindIndex];
  20800. var vertexBuffer = this.getVertexBuffer(kind);
  20801. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20802. updatableNormals = vertexBuffer.isUpdatable();
  20803. kinds.splice(kindIndex, 1);
  20804. kindIndex--;
  20805. continue;
  20806. }
  20807. vbs[kind] = vertexBuffer;
  20808. data[kind] = vbs[kind].getData();
  20809. newdata[kind] = [];
  20810. }
  20811. // Save previous submeshes
  20812. var previousSubmeshes = this.subMeshes.slice(0);
  20813. var indices = this.getIndices();
  20814. var totalIndices = this.getTotalIndices();
  20815. // Generating unique vertices per face
  20816. var index;
  20817. for (index = 0; index < totalIndices; index++) {
  20818. var vertexIndex = indices[index];
  20819. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20820. kind = kinds[kindIndex];
  20821. var stride = vbs[kind].getStrideSize();
  20822. for (var offset = 0; offset < stride; offset++) {
  20823. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20824. }
  20825. }
  20826. }
  20827. // Updating faces & normal
  20828. var normals = [];
  20829. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20830. for (index = 0; index < totalIndices; index += 3) {
  20831. indices[index] = index;
  20832. indices[index + 1] = index + 1;
  20833. indices[index + 2] = index + 2;
  20834. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20835. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20836. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20837. var p1p2 = p1.subtract(p2);
  20838. var p3p2 = p3.subtract(p2);
  20839. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20840. // Store same normals for every vertex
  20841. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20842. normals.push(normal.x);
  20843. normals.push(normal.y);
  20844. normals.push(normal.z);
  20845. }
  20846. }
  20847. this.setIndices(indices);
  20848. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20849. // Updating vertex buffers
  20850. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20851. kind = kinds[kindIndex];
  20852. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20853. }
  20854. // Updating submeshes
  20855. this.releaseSubMeshes();
  20856. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20857. var previousOne = previousSubmeshes[submeshIndex];
  20858. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20859. }
  20860. this.synchronizeInstances();
  20861. return this;
  20862. };
  20863. /**
  20864. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20865. * In other words, more vertices, no more indices and a single bigger VBO.
  20866. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20867. * Returns the Mesh.
  20868. */
  20869. Mesh.prototype.convertToUnIndexedMesh = function () {
  20870. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20871. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20872. var kinds = this.getVerticesDataKinds();
  20873. var vbs = [];
  20874. var data = [];
  20875. var newdata = [];
  20876. var updatableNormals = false;
  20877. var kindIndex;
  20878. var kind;
  20879. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20880. kind = kinds[kindIndex];
  20881. var vertexBuffer = this.getVertexBuffer(kind);
  20882. vbs[kind] = vertexBuffer;
  20883. data[kind] = vbs[kind].getData();
  20884. newdata[kind] = [];
  20885. }
  20886. // Save previous submeshes
  20887. var previousSubmeshes = this.subMeshes.slice(0);
  20888. var indices = this.getIndices();
  20889. var totalIndices = this.getTotalIndices();
  20890. // Generating unique vertices per face
  20891. var index;
  20892. for (index = 0; index < totalIndices; index++) {
  20893. var vertexIndex = indices[index];
  20894. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20895. kind = kinds[kindIndex];
  20896. var stride = vbs[kind].getStrideSize();
  20897. for (var offset = 0; offset < stride; offset++) {
  20898. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20899. }
  20900. }
  20901. }
  20902. // Updating indices
  20903. for (index = 0; index < totalIndices; index += 3) {
  20904. indices[index] = index;
  20905. indices[index + 1] = index + 1;
  20906. indices[index + 2] = index + 2;
  20907. }
  20908. this.setIndices(indices);
  20909. // Updating vertex buffers
  20910. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20911. kind = kinds[kindIndex];
  20912. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20913. }
  20914. // Updating submeshes
  20915. this.releaseSubMeshes();
  20916. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20917. var previousOne = previousSubmeshes[submeshIndex];
  20918. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20919. }
  20920. this._unIndexed = true;
  20921. this.synchronizeInstances();
  20922. return this;
  20923. };
  20924. /**
  20925. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20926. * This method returns the Mesh.
  20927. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20928. */
  20929. Mesh.prototype.flipFaces = function (flipNormals) {
  20930. if (flipNormals === void 0) { flipNormals = false; }
  20931. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20932. var i;
  20933. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20934. for (i = 0; i < vertex_data.normals.length; i++) {
  20935. vertex_data.normals[i] *= -1;
  20936. }
  20937. }
  20938. var temp;
  20939. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20940. // reassign indices
  20941. temp = vertex_data.indices[i + 1];
  20942. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20943. vertex_data.indices[i + 2] = temp;
  20944. }
  20945. vertex_data.applyToMesh(this);
  20946. return this;
  20947. };
  20948. // Instances
  20949. /**
  20950. * Creates a new InstancedMesh object from the mesh model.
  20951. * An instance shares the same properties and the same material than its model.
  20952. * Only these properties of each instance can then be set individually :
  20953. * - position
  20954. * - rotation
  20955. * - rotationQuaternion
  20956. * - setPivotMatrix
  20957. * - scaling
  20958. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20959. * Warning : this method is not supported for Line mesh and LineSystem
  20960. */
  20961. Mesh.prototype.createInstance = function (name) {
  20962. return new BABYLON.InstancedMesh(name, this);
  20963. };
  20964. /**
  20965. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20966. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20967. * This method returns the Mesh.
  20968. */
  20969. Mesh.prototype.synchronizeInstances = function () {
  20970. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20971. var instance = this.instances[instanceIndex];
  20972. instance._syncSubMeshes();
  20973. }
  20974. return this;
  20975. };
  20976. /**
  20977. * Simplify the mesh according to the given array of settings.
  20978. * Function will return immediately and will simplify async. It returns the Mesh.
  20979. * @param settings a collection of simplification settings.
  20980. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20981. * @param type the type of simplification to run.
  20982. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20983. */
  20984. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20985. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20986. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20987. this.getScene().simplificationQueue.addTask({
  20988. settings: settings,
  20989. parallelProcessing: parallelProcessing,
  20990. mesh: this,
  20991. simplificationType: simplificationType,
  20992. successCallback: successCallback
  20993. });
  20994. return this;
  20995. };
  20996. /**
  20997. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20998. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20999. * This should be used together with the simplification to avoid disappearing triangles.
  21000. * Returns the Mesh.
  21001. * @param successCallback an optional success callback to be called after the optimization finished.
  21002. */
  21003. Mesh.prototype.optimizeIndices = function (successCallback) {
  21004. var _this = this;
  21005. var indices = this.getIndices();
  21006. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21007. var vectorPositions = [];
  21008. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21009. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21010. }
  21011. var dupes = [];
  21012. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21013. var realPos = vectorPositions.length - 1 - iteration;
  21014. var testedPosition = vectorPositions[realPos];
  21015. for (var j = 0; j < realPos; ++j) {
  21016. var againstPosition = vectorPositions[j];
  21017. if (testedPosition.equals(againstPosition)) {
  21018. dupes[realPos] = j;
  21019. break;
  21020. }
  21021. }
  21022. }, function () {
  21023. for (var i = 0; i < indices.length; ++i) {
  21024. indices[i] = dupes[indices[i]] || indices[i];
  21025. }
  21026. //indices are now reordered
  21027. var originalSubMeshes = _this.subMeshes.slice(0);
  21028. _this.setIndices(indices);
  21029. _this.subMeshes = originalSubMeshes;
  21030. if (successCallback) {
  21031. successCallback(_this);
  21032. }
  21033. });
  21034. return this;
  21035. };
  21036. Mesh.prototype.serialize = function (serializationObject) {
  21037. serializationObject.name = this.name;
  21038. serializationObject.id = this.id;
  21039. serializationObject.type = this.getClassName();
  21040. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21041. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21042. }
  21043. serializationObject.position = this.position.asArray();
  21044. if (this.rotationQuaternion) {
  21045. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21046. }
  21047. else if (this.rotation) {
  21048. serializationObject.rotation = this.rotation.asArray();
  21049. }
  21050. serializationObject.scaling = this.scaling.asArray();
  21051. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21052. serializationObject.isEnabled = this.isEnabled();
  21053. serializationObject.isVisible = this.isVisible;
  21054. serializationObject.infiniteDistance = this.infiniteDistance;
  21055. serializationObject.pickable = this.isPickable;
  21056. serializationObject.receiveShadows = this.receiveShadows;
  21057. serializationObject.billboardMode = this.billboardMode;
  21058. serializationObject.visibility = this.visibility;
  21059. serializationObject.checkCollisions = this.checkCollisions;
  21060. serializationObject.isBlocker = this.isBlocker;
  21061. // Parent
  21062. if (this.parent) {
  21063. serializationObject.parentId = this.parent.id;
  21064. }
  21065. // Geometry
  21066. var geometry = this._geometry;
  21067. if (geometry) {
  21068. var geometryId = geometry.id;
  21069. serializationObject.geometryId = geometryId;
  21070. // SubMeshes
  21071. serializationObject.subMeshes = [];
  21072. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21073. var subMesh = this.subMeshes[subIndex];
  21074. serializationObject.subMeshes.push({
  21075. materialIndex: subMesh.materialIndex,
  21076. verticesStart: subMesh.verticesStart,
  21077. verticesCount: subMesh.verticesCount,
  21078. indexStart: subMesh.indexStart,
  21079. indexCount: subMesh.indexCount
  21080. });
  21081. }
  21082. }
  21083. // Material
  21084. if (this.material) {
  21085. serializationObject.materialId = this.material.id;
  21086. }
  21087. else {
  21088. this.material = null;
  21089. }
  21090. // Morph targets
  21091. if (this.morphTargetManager) {
  21092. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21093. }
  21094. // Skeleton
  21095. if (this.skeleton) {
  21096. serializationObject.skeletonId = this.skeleton.id;
  21097. }
  21098. // Physics
  21099. //TODO implement correct serialization for physics impostors.
  21100. if (this.getPhysicsImpostor()) {
  21101. var impostor = this.getPhysicsImpostor();
  21102. serializationObject.physicsMass = impostor.getParam("mass");
  21103. serializationObject.physicsFriction = impostor.getParam("friction");
  21104. serializationObject.physicsRestitution = impostor.getParam("mass");
  21105. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21106. }
  21107. // Metadata
  21108. if (this.metadata) {
  21109. serializationObject.metadata = this.metadata;
  21110. }
  21111. // Instances
  21112. serializationObject.instances = [];
  21113. for (var index = 0; index < this.instances.length; index++) {
  21114. var instance = this.instances[index];
  21115. var serializationInstance = {
  21116. name: instance.name,
  21117. position: instance.position.asArray(),
  21118. scaling: instance.scaling.asArray()
  21119. };
  21120. if (instance.rotationQuaternion) {
  21121. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21122. }
  21123. else if (instance.rotation) {
  21124. serializationInstance.rotation = instance.rotation.asArray();
  21125. }
  21126. serializationObject.instances.push(serializationInstance);
  21127. // Animations
  21128. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21129. serializationInstance.ranges = instance.serializeAnimationRanges();
  21130. }
  21131. //
  21132. // Animations
  21133. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21134. serializationObject.ranges = this.serializeAnimationRanges();
  21135. // Layer mask
  21136. serializationObject.layerMask = this.layerMask;
  21137. // Alpha
  21138. serializationObject.alphaIndex = this.alphaIndex;
  21139. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21140. // Overlay
  21141. serializationObject.overlayAlpha = this.overlayAlpha;
  21142. serializationObject.overlayColor = this.overlayColor.asArray();
  21143. serializationObject.renderOverlay = this.renderOverlay;
  21144. // Fog
  21145. serializationObject.applyFog = this.applyFog;
  21146. // Action Manager
  21147. if (this.actionManager) {
  21148. serializationObject.actions = this.actionManager.serialize(this.name);
  21149. }
  21150. };
  21151. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21152. if (!this.geometry) {
  21153. return;
  21154. }
  21155. this._markSubMeshesAsAttributesDirty();
  21156. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21157. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21158. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21159. this.morphTargetManager = undefined;
  21160. return;
  21161. }
  21162. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21163. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21164. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21165. if (morphTarget.hasNormals) {
  21166. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21167. }
  21168. if (morphTarget.hasTangents) {
  21169. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21170. }
  21171. }
  21172. }
  21173. else {
  21174. var index = 0;
  21175. // Positions
  21176. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21177. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21178. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21179. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21180. }
  21181. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21182. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21183. }
  21184. index++;
  21185. }
  21186. }
  21187. };
  21188. // Statics
  21189. /**
  21190. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21191. * The parameter `parsedMesh` is the mesh to be copied.
  21192. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21193. */
  21194. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21195. var mesh;
  21196. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21197. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21198. }
  21199. else {
  21200. mesh = new Mesh(parsedMesh.name, scene);
  21201. }
  21202. mesh.id = parsedMesh.id;
  21203. if (BABYLON.Tags) {
  21204. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21205. }
  21206. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21207. if (parsedMesh.metadata !== undefined) {
  21208. mesh.metadata = parsedMesh.metadata;
  21209. }
  21210. if (parsedMesh.rotationQuaternion) {
  21211. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21212. }
  21213. else if (parsedMesh.rotation) {
  21214. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21215. }
  21216. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21217. if (parsedMesh.localMatrix) {
  21218. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21219. }
  21220. else if (parsedMesh.pivotMatrix) {
  21221. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21222. }
  21223. mesh.setEnabled(parsedMesh.isEnabled);
  21224. mesh.isVisible = parsedMesh.isVisible;
  21225. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21226. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21227. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21228. if (parsedMesh.applyFog !== undefined) {
  21229. mesh.applyFog = parsedMesh.applyFog;
  21230. }
  21231. if (parsedMesh.pickable !== undefined) {
  21232. mesh.isPickable = parsedMesh.pickable;
  21233. }
  21234. if (parsedMesh.alphaIndex !== undefined) {
  21235. mesh.alphaIndex = parsedMesh.alphaIndex;
  21236. }
  21237. mesh.receiveShadows = parsedMesh.receiveShadows;
  21238. mesh.billboardMode = parsedMesh.billboardMode;
  21239. if (parsedMesh.visibility !== undefined) {
  21240. mesh.visibility = parsedMesh.visibility;
  21241. }
  21242. mesh.checkCollisions = parsedMesh.checkCollisions;
  21243. if (parsedMesh.isBlocker !== undefined) {
  21244. mesh.isBlocker = parsedMesh.isBlocker;
  21245. }
  21246. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21247. // freezeWorldMatrix
  21248. if (parsedMesh.freezeWorldMatrix) {
  21249. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21250. }
  21251. // Parent
  21252. if (parsedMesh.parentId) {
  21253. mesh._waitingParentId = parsedMesh.parentId;
  21254. }
  21255. // Actions
  21256. if (parsedMesh.actions !== undefined) {
  21257. mesh._waitingActions = parsedMesh.actions;
  21258. }
  21259. // Overlay
  21260. if (parsedMesh.overlayAlpha !== undefined) {
  21261. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21262. }
  21263. if (parsedMesh.overlayColor !== undefined) {
  21264. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21265. }
  21266. if (parsedMesh.renderOverlay !== undefined) {
  21267. mesh.renderOverlay = parsedMesh.renderOverlay;
  21268. }
  21269. // Geometry
  21270. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21271. if (parsedMesh.delayLoadingFile) {
  21272. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21273. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21274. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21275. if (parsedMesh._binaryInfo) {
  21276. mesh._binaryInfo = parsedMesh._binaryInfo;
  21277. }
  21278. mesh._delayInfo = [];
  21279. if (parsedMesh.hasUVs) {
  21280. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21281. }
  21282. if (parsedMesh.hasUVs2) {
  21283. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21284. }
  21285. if (parsedMesh.hasUVs3) {
  21286. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21287. }
  21288. if (parsedMesh.hasUVs4) {
  21289. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21290. }
  21291. if (parsedMesh.hasUVs5) {
  21292. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21293. }
  21294. if (parsedMesh.hasUVs6) {
  21295. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21296. }
  21297. if (parsedMesh.hasColors) {
  21298. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21299. }
  21300. if (parsedMesh.hasMatricesIndices) {
  21301. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21302. }
  21303. if (parsedMesh.hasMatricesWeights) {
  21304. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21305. }
  21306. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21307. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21308. mesh._checkDelayState();
  21309. }
  21310. }
  21311. else {
  21312. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21313. }
  21314. // Material
  21315. if (parsedMesh.materialId) {
  21316. mesh.setMaterialByID(parsedMesh.materialId);
  21317. }
  21318. else {
  21319. mesh.material = null;
  21320. }
  21321. // Morph targets
  21322. if (parsedMesh.morphTargetManagerId > -1) {
  21323. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21324. }
  21325. // Skeleton
  21326. if (parsedMesh.skeletonId > -1) {
  21327. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21328. if (parsedMesh.numBoneInfluencers) {
  21329. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21330. }
  21331. }
  21332. // Animations
  21333. if (parsedMesh.animations) {
  21334. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21335. var parsedAnimation = parsedMesh.animations[animationIndex];
  21336. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21337. }
  21338. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21339. }
  21340. if (parsedMesh.autoAnimate) {
  21341. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21342. }
  21343. // Layer Mask
  21344. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21345. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21346. }
  21347. else {
  21348. mesh.layerMask = 0x0FFFFFFF;
  21349. }
  21350. // Physics
  21351. if (parsedMesh.physicsImpostor) {
  21352. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21353. mass: parsedMesh.physicsMass,
  21354. friction: parsedMesh.physicsFriction,
  21355. restitution: parsedMesh.physicsRestitution
  21356. }, scene);
  21357. }
  21358. // Instances
  21359. if (parsedMesh.instances) {
  21360. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21361. var parsedInstance = parsedMesh.instances[index];
  21362. var instance = mesh.createInstance(parsedInstance.name);
  21363. if (BABYLON.Tags) {
  21364. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21365. }
  21366. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21367. if (parsedInstance.parentId) {
  21368. instance._waitingParentId = parsedInstance.parentId;
  21369. }
  21370. if (parsedInstance.rotationQuaternion) {
  21371. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21372. }
  21373. else if (parsedInstance.rotation) {
  21374. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21375. }
  21376. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21377. instance.checkCollisions = mesh.checkCollisions;
  21378. if (parsedMesh.animations) {
  21379. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21380. parsedAnimation = parsedMesh.animations[animationIndex];
  21381. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21382. }
  21383. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21384. }
  21385. }
  21386. }
  21387. return mesh;
  21388. };
  21389. /**
  21390. * Creates a ribbon mesh.
  21391. * Please consider using the same method from the MeshBuilder class instead.
  21392. * 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.
  21393. *
  21394. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21395. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21396. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21397. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21398. * 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.
  21399. * 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.
  21400. * 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
  21401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21402. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21403. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21404. */
  21405. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21406. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21407. pathArray: pathArray,
  21408. closeArray: closeArray,
  21409. closePath: closePath,
  21410. offset: offset,
  21411. updatable: updatable,
  21412. sideOrientation: sideOrientation,
  21413. instance: instance
  21414. }, scene);
  21415. };
  21416. /**
  21417. * Creates a plane polygonal mesh. By default, this is a disc.
  21418. * Please consider using the same method from the MeshBuilder class instead.
  21419. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21420. * 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.
  21421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21424. */
  21425. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21426. var options = {
  21427. radius: radius,
  21428. tessellation: tessellation,
  21429. sideOrientation: sideOrientation,
  21430. updatable: updatable
  21431. };
  21432. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21433. };
  21434. /**
  21435. * Creates a box mesh.
  21436. * Please consider using the same method from the MeshBuilder class instead.
  21437. * The parameter `size` sets the size (float) of each box side (default 1).
  21438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21439. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21441. */
  21442. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21443. var options = {
  21444. size: size,
  21445. sideOrientation: sideOrientation,
  21446. updatable: updatable
  21447. };
  21448. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21449. };
  21450. /**
  21451. * Creates a sphere mesh.
  21452. * Please consider using the same method from the MeshBuilder class instead.
  21453. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21454. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21455. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21456. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21457. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21458. */
  21459. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21460. var options = {
  21461. segments: segments,
  21462. diameterX: diameter,
  21463. diameterY: diameter,
  21464. diameterZ: diameter,
  21465. sideOrientation: sideOrientation,
  21466. updatable: updatable
  21467. };
  21468. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21469. };
  21470. /**
  21471. * Creates a cylinder or a cone mesh.
  21472. * Please consider using the same method from the MeshBuilder class instead.
  21473. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21474. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21475. * 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.
  21476. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21477. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21478. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21479. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21481. */
  21482. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21483. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21484. if (scene !== undefined) {
  21485. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21486. updatable = scene;
  21487. }
  21488. scene = subdivisions;
  21489. subdivisions = 1;
  21490. }
  21491. var options = {
  21492. height: height,
  21493. diameterTop: diameterTop,
  21494. diameterBottom: diameterBottom,
  21495. tessellation: tessellation,
  21496. subdivisions: subdivisions,
  21497. sideOrientation: sideOrientation,
  21498. updatable: updatable
  21499. };
  21500. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21501. };
  21502. // Torus (Code from SharpDX.org)
  21503. /**
  21504. * Creates a torus mesh.
  21505. * Please consider using the same method from the MeshBuilder class instead.
  21506. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21507. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21508. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21509. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21510. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21512. */
  21513. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21514. var options = {
  21515. diameter: diameter,
  21516. thickness: thickness,
  21517. tessellation: tessellation,
  21518. sideOrientation: sideOrientation,
  21519. updatable: updatable
  21520. };
  21521. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21522. };
  21523. /**
  21524. * Creates a torus knot mesh.
  21525. * Please consider using the same method from the MeshBuilder class instead.
  21526. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21527. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21528. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21529. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21533. */
  21534. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21535. var options = {
  21536. radius: radius,
  21537. tube: tube,
  21538. radialSegments: radialSegments,
  21539. tubularSegments: tubularSegments,
  21540. p: p,
  21541. q: q,
  21542. sideOrientation: sideOrientation,
  21543. updatable: updatable
  21544. };
  21545. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21546. };
  21547. /**
  21548. * Creates a line mesh.
  21549. * Please consider using the same method from the MeshBuilder class instead.
  21550. * 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.
  21551. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21552. * The parameter `points` is an array successive Vector3.
  21553. * 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
  21554. * When updating an instance, remember that only point positions can change, not the number of points.
  21555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21556. */
  21557. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21558. var options = {
  21559. points: points,
  21560. updatable: updatable,
  21561. instance: instance
  21562. };
  21563. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21564. };
  21565. /**
  21566. * Creates a dashed line mesh.
  21567. * Please consider using the same method from the MeshBuilder class instead.
  21568. * 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.
  21569. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21570. * The parameter `points` is an array successive Vector3.
  21571. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21572. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21573. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21574. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  21575. * When updating an instance, remember that only point positions can change, not the number of points.
  21576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21577. */
  21578. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21579. var options = {
  21580. points: points,
  21581. dashSize: dashSize,
  21582. gapSize: gapSize,
  21583. dashNb: dashNb,
  21584. updatable: updatable,
  21585. instance: instance
  21586. };
  21587. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21588. };
  21589. /**
  21590. * Creates a polygon mesh.
  21591. * Please consider using the same method from the MeshBuilder class instead.
  21592. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21593. * 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.
  21594. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21596. * Remember you can only change the shape positions, not their number when updating a polygon.
  21597. */
  21598. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21599. var options = {
  21600. shape: shape,
  21601. holes: holes,
  21602. updatable: updatable,
  21603. sideOrientation: sideOrientation
  21604. };
  21605. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21606. };
  21607. /**
  21608. * Creates an extruded polygon mesh, with depth in the Y direction.
  21609. * Please consider using the same method from the MeshBuilder class instead.
  21610. */
  21611. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21612. var options = {
  21613. shape: shape,
  21614. holes: holes,
  21615. depth: depth,
  21616. updatable: updatable,
  21617. sideOrientation: sideOrientation
  21618. };
  21619. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21620. };
  21621. /**
  21622. * Creates an extruded shape mesh.
  21623. * 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.
  21624. * Please consider using the same method from the MeshBuilder class instead.
  21625. *
  21626. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21627. * 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
  21628. * extruded along the Z axis.
  21629. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21630. * 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.
  21631. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21632. * 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
  21633. * 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
  21634. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21636. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21638. */
  21639. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21640. var options = {
  21641. shape: shape,
  21642. path: path,
  21643. scale: scale,
  21644. rotation: rotation,
  21645. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21646. sideOrientation: sideOrientation,
  21647. instance: instance,
  21648. updatable: updatable
  21649. };
  21650. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21651. };
  21652. /**
  21653. * Creates an custom extruded shape mesh.
  21654. * 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.
  21655. * Please consider using the same method from the MeshBuilder class instead.
  21656. *
  21657. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21658. * 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
  21659. * extruded along the Z axis.
  21660. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21661. * 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
  21662. * and the distance of this point from the begining of the path :
  21663. * ```javascript
  21664. * var rotationFunction = function(i, distance) {
  21665. * // do things
  21666. * return rotationValue; }
  21667. * ```
  21668. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21669. * 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
  21670. * and the distance of this point from the begining of the path :
  21671. * ```javascript
  21672. * var scaleFunction = function(i, distance) {
  21673. * // do things
  21674. * return scaleValue;}
  21675. * ```
  21676. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21677. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21678. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21679. * 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
  21680. * 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
  21681. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21683. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21685. */
  21686. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21687. var options = {
  21688. shape: shape,
  21689. path: path,
  21690. scaleFunction: scaleFunction,
  21691. rotationFunction: rotationFunction,
  21692. ribbonCloseArray: ribbonCloseArray,
  21693. ribbonClosePath: ribbonClosePath,
  21694. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21695. sideOrientation: sideOrientation,
  21696. instance: instance,
  21697. updatable: updatable
  21698. };
  21699. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21700. };
  21701. /**
  21702. * Creates lathe mesh.
  21703. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21704. * Please consider using the same method from the MeshBuilder class instead.
  21705. * 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
  21706. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21707. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21708. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21710. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21712. */
  21713. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21714. var options = {
  21715. shape: shape,
  21716. radius: radius,
  21717. tessellation: tessellation,
  21718. sideOrientation: sideOrientation,
  21719. updatable: updatable
  21720. };
  21721. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21722. };
  21723. /**
  21724. * Creates a plane mesh.
  21725. * Please consider using the same method from the MeshBuilder class instead.
  21726. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21727. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21730. */
  21731. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21732. var options = {
  21733. size: size,
  21734. width: size,
  21735. height: size,
  21736. sideOrientation: sideOrientation,
  21737. updatable: updatable
  21738. };
  21739. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21740. };
  21741. /**
  21742. * Creates a ground mesh.
  21743. * Please consider using the same method from the MeshBuilder class instead.
  21744. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21745. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21747. */
  21748. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21749. var options = {
  21750. width: width,
  21751. height: height,
  21752. subdivisions: subdivisions,
  21753. updatable: updatable
  21754. };
  21755. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21756. };
  21757. /**
  21758. * Creates a tiled ground mesh.
  21759. * Please consider using the same method from the MeshBuilder class instead.
  21760. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21761. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21762. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21763. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21764. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21765. * numbers of subdivisions on the ground width and height of each tile.
  21766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21767. */
  21768. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21769. var options = {
  21770. xmin: xmin,
  21771. zmin: zmin,
  21772. xmax: xmax,
  21773. zmax: zmax,
  21774. subdivisions: subdivisions,
  21775. precision: precision,
  21776. updatable: updatable
  21777. };
  21778. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21779. };
  21780. /**
  21781. * Creates a ground mesh from a height map.
  21782. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21783. * Please consider using the same method from the MeshBuilder class instead.
  21784. * The parameter `url` sets the URL of the height map image resource.
  21785. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21786. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21787. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21788. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21789. * 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).
  21790. * This function is passed the newly built mesh :
  21791. * ```javascript
  21792. * function(mesh) { // do things
  21793. * return; }
  21794. * ```
  21795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21796. */
  21797. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21798. var options = {
  21799. width: width,
  21800. height: height,
  21801. subdivisions: subdivisions,
  21802. minHeight: minHeight,
  21803. maxHeight: maxHeight,
  21804. updatable: updatable,
  21805. onReady: onReady
  21806. };
  21807. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21808. };
  21809. /**
  21810. * Creates a tube mesh.
  21811. * 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.
  21812. * Please consider using the same method from the MeshBuilder class instead.
  21813. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21814. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21815. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21816. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21817. * 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.
  21818. * It must return a radius value (positive float) :
  21819. * ```javascript
  21820. * var radiusFunction = function(i, distance) {
  21821. * // do things
  21822. * return radius; }
  21823. * ```
  21824. * 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
  21825. * 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
  21826. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21829. */
  21830. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21831. var options = {
  21832. path: path,
  21833. radius: radius,
  21834. tessellation: tessellation,
  21835. radiusFunction: radiusFunction,
  21836. arc: 1,
  21837. cap: cap,
  21838. updatable: updatable,
  21839. sideOrientation: sideOrientation,
  21840. instance: instance
  21841. };
  21842. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21843. };
  21844. /**
  21845. * Creates a polyhedron mesh.
  21846. * Please consider using the same method from the MeshBuilder class instead.
  21847. * 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
  21848. * to choose the wanted type.
  21849. * The parameter `size` (positive float, default 1) sets the polygon size.
  21850. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21851. * 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`.
  21852. * 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
  21853. * 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)`).
  21854. * 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
  21855. * 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.
  21856. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21857. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21859. */
  21860. Mesh.CreatePolyhedron = function (name, options, scene) {
  21861. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21862. };
  21863. /**
  21864. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21865. * Please consider using the same method from the MeshBuilder class instead.
  21866. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21867. * 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`).
  21868. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21869. * 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.
  21870. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21873. */
  21874. Mesh.CreateIcoSphere = function (name, options, scene) {
  21875. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21876. };
  21877. /**
  21878. * Creates a decal mesh.
  21879. * Please consider using the same method from the MeshBuilder class instead.
  21880. * 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.
  21881. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21882. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21883. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21884. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21885. */
  21886. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21887. var options = {
  21888. position: position,
  21889. normal: normal,
  21890. size: size,
  21891. angle: angle
  21892. };
  21893. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21894. };
  21895. // Skeletons
  21896. /**
  21897. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21898. */
  21899. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21900. var source;
  21901. if (!this._sourcePositions) {
  21902. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21903. this._sourcePositions = new Float32Array(source);
  21904. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21905. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21906. }
  21907. }
  21908. return this._sourcePositions;
  21909. };
  21910. /**
  21911. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21912. */
  21913. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21914. var source;
  21915. if (!this._sourceNormals) {
  21916. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21917. this._sourceNormals = new Float32Array(source);
  21918. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21919. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21920. }
  21921. }
  21922. return this._sourceNormals;
  21923. };
  21924. /**
  21925. * Updates the vertex buffer by applying transformation from the bones.
  21926. * Returns the Mesh.
  21927. *
  21928. * @param {skeleton} skeleton to apply
  21929. */
  21930. Mesh.prototype.applySkeleton = function (skeleton) {
  21931. if (!this.geometry) {
  21932. return this;
  21933. }
  21934. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21935. return this;
  21936. }
  21937. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21938. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21939. return this;
  21940. }
  21941. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21942. return this;
  21943. }
  21944. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21945. return this;
  21946. }
  21947. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21948. return this;
  21949. }
  21950. if (!this._sourcePositions) {
  21951. var submeshes = this.subMeshes.slice();
  21952. this.setPositionsForCPUSkinning();
  21953. this.subMeshes = submeshes;
  21954. }
  21955. if (!this._sourceNormals) {
  21956. this.setNormalsForCPUSkinning();
  21957. }
  21958. // positionsData checks for not being Float32Array will only pass at most once
  21959. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21960. if (!(positionsData instanceof Float32Array)) {
  21961. positionsData = new Float32Array(positionsData);
  21962. }
  21963. // normalsData checks for not being Float32Array will only pass at most once
  21964. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21965. if (!(normalsData instanceof Float32Array)) {
  21966. normalsData = new Float32Array(normalsData);
  21967. }
  21968. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21969. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21970. var needExtras = this.numBoneInfluencers > 4;
  21971. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21972. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21973. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21974. var tempVector3 = BABYLON.Vector3.Zero();
  21975. var finalMatrix = new BABYLON.Matrix();
  21976. var tempMatrix = new BABYLON.Matrix();
  21977. var matWeightIdx = 0;
  21978. var inf;
  21979. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21980. var weight;
  21981. for (inf = 0; inf < 4; inf++) {
  21982. weight = matricesWeightsData[matWeightIdx + inf];
  21983. if (weight > 0) {
  21984. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21985. finalMatrix.addToSelf(tempMatrix);
  21986. }
  21987. else
  21988. break;
  21989. }
  21990. if (needExtras) {
  21991. for (inf = 0; inf < 4; inf++) {
  21992. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21993. if (weight > 0) {
  21994. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21995. finalMatrix.addToSelf(tempMatrix);
  21996. }
  21997. else
  21998. break;
  21999. }
  22000. }
  22001. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22002. tempVector3.toArray(positionsData, index);
  22003. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22004. tempVector3.toArray(normalsData, index);
  22005. finalMatrix.reset();
  22006. }
  22007. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22008. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22009. return this;
  22010. };
  22011. // Tools
  22012. /**
  22013. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22014. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22015. */
  22016. Mesh.MinMax = function (meshes) {
  22017. var minVector = null;
  22018. var maxVector = null;
  22019. meshes.forEach(function (mesh, index, array) {
  22020. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22021. if (!minVector) {
  22022. minVector = boundingBox.minimumWorld;
  22023. maxVector = boundingBox.maximumWorld;
  22024. }
  22025. else {
  22026. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22027. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22028. }
  22029. });
  22030. return {
  22031. min: minVector,
  22032. max: maxVector
  22033. };
  22034. };
  22035. /**
  22036. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22037. */
  22038. Mesh.Center = function (meshesOrMinMaxVector) {
  22039. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22040. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22041. };
  22042. /**
  22043. * Merge the array of meshes into a single mesh for performance reasons.
  22044. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22045. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22046. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22047. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22048. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22049. */
  22050. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22051. if (disposeSource === void 0) { disposeSource = true; }
  22052. var index;
  22053. if (!allow32BitsIndices) {
  22054. var totalVertices = 0;
  22055. // Counting vertices
  22056. for (index = 0; index < meshes.length; index++) {
  22057. if (meshes[index]) {
  22058. totalVertices += meshes[index].getTotalVertices();
  22059. if (totalVertices > 65536) {
  22060. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22061. return null;
  22062. }
  22063. }
  22064. }
  22065. }
  22066. // Merge
  22067. var vertexData;
  22068. var otherVertexData;
  22069. var indiceArray = new Array();
  22070. var source;
  22071. for (index = 0; index < meshes.length; index++) {
  22072. if (meshes[index]) {
  22073. meshes[index].computeWorldMatrix(true);
  22074. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22075. otherVertexData.transform(meshes[index].getWorldMatrix());
  22076. if (vertexData) {
  22077. vertexData.merge(otherVertexData);
  22078. }
  22079. else {
  22080. vertexData = otherVertexData;
  22081. source = meshes[index];
  22082. }
  22083. if (subdivideWithSubMeshes) {
  22084. indiceArray.push(meshes[index].getTotalIndices());
  22085. }
  22086. }
  22087. }
  22088. if (!meshSubclass) {
  22089. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22090. }
  22091. vertexData.applyToMesh(meshSubclass);
  22092. // Setting properties
  22093. meshSubclass.material = source.material;
  22094. meshSubclass.checkCollisions = source.checkCollisions;
  22095. // Cleaning
  22096. if (disposeSource) {
  22097. for (index = 0; index < meshes.length; index++) {
  22098. if (meshes[index]) {
  22099. meshes[index].dispose();
  22100. }
  22101. }
  22102. }
  22103. // Subdivide
  22104. if (subdivideWithSubMeshes) {
  22105. //-- Suppresions du submesh global
  22106. meshSubclass.releaseSubMeshes();
  22107. index = 0;
  22108. var offset = 0;
  22109. //-- aplique la subdivision en fonction du tableau d'indices
  22110. while (index < indiceArray.length) {
  22111. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22112. offset += indiceArray[index];
  22113. index++;
  22114. }
  22115. }
  22116. return meshSubclass;
  22117. };
  22118. return Mesh;
  22119. }(BABYLON.AbstractMesh));
  22120. // Consts
  22121. Mesh._FRONTSIDE = 0;
  22122. Mesh._BACKSIDE = 1;
  22123. Mesh._DOUBLESIDE = 2;
  22124. Mesh._DEFAULTSIDE = 0;
  22125. Mesh._NO_CAP = 0;
  22126. Mesh._CAP_START = 1;
  22127. Mesh._CAP_END = 2;
  22128. Mesh._CAP_ALL = 3;
  22129. BABYLON.Mesh = Mesh;
  22130. })(BABYLON || (BABYLON = {}));
  22131. //# sourceMappingURL=babylon.mesh.js.map
  22132. var BABYLON;
  22133. (function (BABYLON) {
  22134. var SubMesh = (function () {
  22135. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22136. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22137. this.materialIndex = materialIndex;
  22138. this.verticesStart = verticesStart;
  22139. this.verticesCount = verticesCount;
  22140. this.indexStart = indexStart;
  22141. this.indexCount = indexCount;
  22142. this._renderId = 0;
  22143. this._mesh = mesh;
  22144. this._renderingMesh = renderingMesh || mesh;
  22145. mesh.subMeshes.push(this);
  22146. this._trianglePlanes = [];
  22147. this._id = mesh.subMeshes.length - 1;
  22148. if (createBoundingBox) {
  22149. this.refreshBoundingInfo();
  22150. mesh.computeWorldMatrix(true);
  22151. }
  22152. }
  22153. Object.defineProperty(SubMesh.prototype, "effect", {
  22154. get: function () {
  22155. return this._materialEffect;
  22156. },
  22157. enumerable: true,
  22158. configurable: true
  22159. });
  22160. SubMesh.prototype.setEffect = function (effect, defines) {
  22161. if (this._materialEffect === effect) {
  22162. return;
  22163. }
  22164. this._materialDefines = defines;
  22165. this._materialEffect = effect;
  22166. };
  22167. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22168. get: function () {
  22169. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22170. },
  22171. enumerable: true,
  22172. configurable: true
  22173. });
  22174. /**
  22175. * Returns the submesh BoudingInfo object.
  22176. */
  22177. SubMesh.prototype.getBoundingInfo = function () {
  22178. if (this.IsGlobal) {
  22179. return this._mesh.getBoundingInfo();
  22180. }
  22181. return this._boundingInfo;
  22182. };
  22183. /**
  22184. * Sets the submesh BoundingInfo.
  22185. * Return the SubMesh.
  22186. */
  22187. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22188. this._boundingInfo = boundingInfo;
  22189. return this;
  22190. };
  22191. /**
  22192. * Returns the mesh of the current submesh.
  22193. */
  22194. SubMesh.prototype.getMesh = function () {
  22195. return this._mesh;
  22196. };
  22197. /**
  22198. * Returns the rendering mesh of the submesh.
  22199. */
  22200. SubMesh.prototype.getRenderingMesh = function () {
  22201. return this._renderingMesh;
  22202. };
  22203. /**
  22204. * Returns the submesh material.
  22205. */
  22206. SubMesh.prototype.getMaterial = function () {
  22207. var rootMaterial = this._renderingMesh.material;
  22208. if (rootMaterial && rootMaterial.getSubMaterial) {
  22209. var multiMaterial = rootMaterial;
  22210. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22211. if (this._currentMaterial !== effectiveMaterial) {
  22212. this._currentMaterial = effectiveMaterial;
  22213. if (this._materialDefines) {
  22214. this._materialDefines.markAllAsDirty();
  22215. }
  22216. }
  22217. return effectiveMaterial;
  22218. }
  22219. if (!rootMaterial) {
  22220. return this._mesh.getScene().defaultMaterial;
  22221. }
  22222. return rootMaterial;
  22223. };
  22224. // Methods
  22225. /**
  22226. * Sets a new updated BoundingInfo object to the submesh.
  22227. * Returns the SubMesh.
  22228. */
  22229. SubMesh.prototype.refreshBoundingInfo = function () {
  22230. this._lastColliderWorldVertices = null;
  22231. if (this.IsGlobal) {
  22232. return;
  22233. }
  22234. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22235. if (!data) {
  22236. this._boundingInfo = this._mesh._boundingInfo;
  22237. return;
  22238. }
  22239. var indices = this._renderingMesh.getIndices();
  22240. var extend;
  22241. //is this the only submesh?
  22242. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22243. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22244. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22245. }
  22246. else {
  22247. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22248. }
  22249. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22250. return this;
  22251. };
  22252. SubMesh.prototype._checkCollision = function (collider) {
  22253. return this.getBoundingInfo()._checkCollision(collider);
  22254. };
  22255. /**
  22256. * Updates the submesh BoundingInfo.
  22257. * Returns the Submesh.
  22258. */
  22259. SubMesh.prototype.updateBoundingInfo = function (world) {
  22260. if (!this.getBoundingInfo()) {
  22261. this.refreshBoundingInfo();
  22262. }
  22263. this.getBoundingInfo().update(world);
  22264. return this;
  22265. };
  22266. /**
  22267. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22268. * Boolean returned.
  22269. */
  22270. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22271. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22272. };
  22273. /**
  22274. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22275. * Boolean returned.
  22276. */
  22277. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22278. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22279. };
  22280. /**
  22281. * Renders the submesh.
  22282. * Returns it.
  22283. */
  22284. SubMesh.prototype.render = function (enableAlphaMode) {
  22285. this._renderingMesh.render(this, enableAlphaMode);
  22286. return this;
  22287. };
  22288. /**
  22289. * Returns a new Index Buffer.
  22290. * Type returned : WebGLBuffer.
  22291. */
  22292. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22293. if (!this._linesIndexBuffer) {
  22294. var linesIndices = [];
  22295. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22296. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22297. }
  22298. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22299. this.linesIndexCount = linesIndices.length;
  22300. }
  22301. return this._linesIndexBuffer;
  22302. };
  22303. /**
  22304. * True is the passed Ray intersects the submesh bounding box.
  22305. * Boolean returned.
  22306. */
  22307. SubMesh.prototype.canIntersects = function (ray) {
  22308. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22309. };
  22310. /**
  22311. * Returns an object IntersectionInfo.
  22312. */
  22313. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22314. var intersectInfo = null;
  22315. // LineMesh first as it's also a Mesh...
  22316. if (this._mesh instanceof BABYLON.LinesMesh) {
  22317. var lineMesh = this._mesh;
  22318. // Line test
  22319. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22320. var p0 = positions[indices[index]];
  22321. var p1 = positions[indices[index + 1]];
  22322. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22323. if (length < 0) {
  22324. continue;
  22325. }
  22326. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22327. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22328. if (fastCheck) {
  22329. break;
  22330. }
  22331. }
  22332. }
  22333. }
  22334. else {
  22335. // Triangles test
  22336. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22337. var p0 = positions[indices[index]];
  22338. var p1 = positions[indices[index + 1]];
  22339. var p2 = positions[indices[index + 2]];
  22340. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22341. if (currentIntersectInfo) {
  22342. if (currentIntersectInfo.distance < 0) {
  22343. continue;
  22344. }
  22345. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22346. intersectInfo = currentIntersectInfo;
  22347. intersectInfo.faceId = index / 3;
  22348. if (fastCheck) {
  22349. break;
  22350. }
  22351. }
  22352. }
  22353. }
  22354. }
  22355. return intersectInfo;
  22356. };
  22357. // Clone
  22358. /**
  22359. * Creates a new Submesh from the passed Mesh.
  22360. */
  22361. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22362. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22363. if (!this.IsGlobal) {
  22364. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22365. }
  22366. return result;
  22367. };
  22368. // Dispose
  22369. /**
  22370. * Disposes the Submesh.
  22371. * Returns nothing.
  22372. */
  22373. SubMesh.prototype.dispose = function () {
  22374. if (this._linesIndexBuffer) {
  22375. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22376. this._linesIndexBuffer = null;
  22377. }
  22378. // Remove from mesh
  22379. var index = this._mesh.subMeshes.indexOf(this);
  22380. this._mesh.subMeshes.splice(index, 1);
  22381. };
  22382. // Statics
  22383. /**
  22384. * Creates a new Submesh from the passed parameters :
  22385. * - materialIndex (integer) : the index of the main mesh material.
  22386. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22387. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22388. * - mesh (Mesh) : the main mesh to create the submesh from.
  22389. * - renderingMesh (optional Mesh) : rendering mesh.
  22390. */
  22391. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22392. var minVertexIndex = Number.MAX_VALUE;
  22393. var maxVertexIndex = -Number.MAX_VALUE;
  22394. renderingMesh = renderingMesh || mesh;
  22395. var indices = renderingMesh.getIndices();
  22396. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22397. var vertexIndex = indices[index];
  22398. if (vertexIndex < minVertexIndex)
  22399. minVertexIndex = vertexIndex;
  22400. if (vertexIndex > maxVertexIndex)
  22401. maxVertexIndex = vertexIndex;
  22402. }
  22403. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22404. };
  22405. return SubMesh;
  22406. }());
  22407. BABYLON.SubMesh = SubMesh;
  22408. })(BABYLON || (BABYLON = {}));
  22409. //# sourceMappingURL=babylon.subMesh.js.map
  22410. var BABYLON;
  22411. (function (BABYLON) {
  22412. var EffectFallbacks = (function () {
  22413. function EffectFallbacks() {
  22414. this._defines = {};
  22415. this._currentRank = 32;
  22416. this._maxRank = -1;
  22417. }
  22418. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22419. if (!this._defines[rank]) {
  22420. if (rank < this._currentRank) {
  22421. this._currentRank = rank;
  22422. }
  22423. if (rank > this._maxRank) {
  22424. this._maxRank = rank;
  22425. }
  22426. this._defines[rank] = new Array();
  22427. }
  22428. this._defines[rank].push(define);
  22429. };
  22430. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22431. this._meshRank = rank;
  22432. this._mesh = mesh;
  22433. if (rank < this._currentRank) {
  22434. this._currentRank = rank;
  22435. }
  22436. if (rank > this._maxRank) {
  22437. this._maxRank = rank;
  22438. }
  22439. };
  22440. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22441. get: function () {
  22442. return this._currentRank <= this._maxRank;
  22443. },
  22444. enumerable: true,
  22445. configurable: true
  22446. });
  22447. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22448. // First we try to switch to CPU skinning
  22449. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22450. this._mesh.computeBonesUsingShaders = false;
  22451. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22452. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22453. var scene = this._mesh.getScene();
  22454. for (var index = 0; index < scene.meshes.length; index++) {
  22455. var otherMesh = scene.meshes[index];
  22456. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22457. otherMesh.computeBonesUsingShaders = false;
  22458. }
  22459. }
  22460. }
  22461. else {
  22462. var currentFallbacks = this._defines[this._currentRank];
  22463. if (currentFallbacks) {
  22464. for (var index = 0; index < currentFallbacks.length; index++) {
  22465. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22466. }
  22467. }
  22468. this._currentRank++;
  22469. }
  22470. return currentDefines;
  22471. };
  22472. return EffectFallbacks;
  22473. }());
  22474. BABYLON.EffectFallbacks = EffectFallbacks;
  22475. var EffectCreationOptions = (function () {
  22476. function EffectCreationOptions() {
  22477. }
  22478. return EffectCreationOptions;
  22479. }());
  22480. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22481. var Effect = (function () {
  22482. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22483. var _this = this;
  22484. this.uniqueId = 0;
  22485. this._uniformBuffersNames = {};
  22486. this._isReady = false;
  22487. this._compilationError = "";
  22488. this._valueCache = {};
  22489. this.name = baseName;
  22490. if (attributesNamesOrOptions.attributes) {
  22491. var options = attributesNamesOrOptions;
  22492. this._engine = uniformsNamesOrEngine;
  22493. this._attributesNames = options.attributes;
  22494. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22495. this._samplers = options.samplers;
  22496. this.defines = options.defines;
  22497. this.onError = options.onError;
  22498. this.onCompiled = options.onCompiled;
  22499. this._fallbacks = options.fallbacks;
  22500. this._indexParameters = options.indexParameters;
  22501. if (options.uniformBuffersNames) {
  22502. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22503. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22504. }
  22505. }
  22506. }
  22507. else {
  22508. this._engine = engine;
  22509. this.defines = defines;
  22510. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22511. this._samplers = samplers;
  22512. this._attributesNames = attributesNamesOrOptions;
  22513. this.onError = onError;
  22514. this.onCompiled = onCompiled;
  22515. this._indexParameters = indexParameters;
  22516. this._fallbacks = fallbacks;
  22517. }
  22518. this.uniqueId = Effect._uniqueIdSeed++;
  22519. var vertexSource;
  22520. var fragmentSource;
  22521. if (baseName.vertexElement) {
  22522. vertexSource = document.getElementById(baseName.vertexElement);
  22523. if (!vertexSource) {
  22524. vertexSource = baseName.vertexElement;
  22525. }
  22526. }
  22527. else {
  22528. vertexSource = baseName.vertex || baseName;
  22529. }
  22530. if (baseName.fragmentElement) {
  22531. fragmentSource = document.getElementById(baseName.fragmentElement);
  22532. if (!fragmentSource) {
  22533. fragmentSource = baseName.fragmentElement;
  22534. }
  22535. }
  22536. else {
  22537. fragmentSource = baseName.fragment || baseName;
  22538. }
  22539. this._loadVertexShader(vertexSource, function (vertexCode) {
  22540. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22541. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22542. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22543. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22544. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22545. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22546. });
  22547. });
  22548. });
  22549. });
  22550. });
  22551. });
  22552. }
  22553. Object.defineProperty(Effect.prototype, "key", {
  22554. get: function () {
  22555. return this._key;
  22556. },
  22557. enumerable: true,
  22558. configurable: true
  22559. });
  22560. // Properties
  22561. Effect.prototype.isReady = function () {
  22562. return this._isReady;
  22563. };
  22564. Effect.prototype.getProgram = function () {
  22565. return this._program;
  22566. };
  22567. Effect.prototype.getAttributesNames = function () {
  22568. return this._attributesNames;
  22569. };
  22570. Effect.prototype.getAttributeLocation = function (index) {
  22571. return this._attributes[index];
  22572. };
  22573. Effect.prototype.getAttributeLocationByName = function (name) {
  22574. var index = this._attributesNames.indexOf(name);
  22575. return this._attributes[index];
  22576. };
  22577. Effect.prototype.getAttributesCount = function () {
  22578. return this._attributes.length;
  22579. };
  22580. Effect.prototype.getUniformIndex = function (uniformName) {
  22581. return this._uniformsNames.indexOf(uniformName);
  22582. };
  22583. Effect.prototype.getUniform = function (uniformName) {
  22584. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22585. };
  22586. Effect.prototype.getSamplers = function () {
  22587. return this._samplers;
  22588. };
  22589. Effect.prototype.getCompilationError = function () {
  22590. return this._compilationError;
  22591. };
  22592. Effect.prototype.getVertexShaderSource = function () {
  22593. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22594. };
  22595. Effect.prototype.getFragmentShaderSource = function () {
  22596. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22597. };
  22598. // Methods
  22599. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22600. // DOM element ?
  22601. if (vertex instanceof HTMLElement) {
  22602. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22603. callback(vertexCode);
  22604. return;
  22605. }
  22606. // Base64 encoded ?
  22607. if (vertex.substr(0, 7) === "base64:") {
  22608. var vertexBinary = window.atob(vertex.substr(7));
  22609. callback(vertexBinary);
  22610. return;
  22611. }
  22612. // Is in local store ?
  22613. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22614. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22615. return;
  22616. }
  22617. var vertexShaderUrl;
  22618. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22619. vertexShaderUrl = vertex;
  22620. }
  22621. else {
  22622. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22623. }
  22624. // Vertex shader
  22625. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22626. };
  22627. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22628. // DOM element ?
  22629. if (fragment instanceof HTMLElement) {
  22630. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22631. callback(fragmentCode);
  22632. return;
  22633. }
  22634. // Base64 encoded ?
  22635. if (fragment.substr(0, 7) === "base64:") {
  22636. var fragmentBinary = window.atob(fragment.substr(7));
  22637. callback(fragmentBinary);
  22638. return;
  22639. }
  22640. // Is in local store ?
  22641. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22642. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22643. return;
  22644. }
  22645. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22646. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22647. return;
  22648. }
  22649. var fragmentShaderUrl;
  22650. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22651. fragmentShaderUrl = fragment;
  22652. }
  22653. else {
  22654. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22655. }
  22656. // Fragment shader
  22657. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22658. };
  22659. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22660. // Rebuild shaders source code
  22661. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22662. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22663. vertexCode = prefix + vertexCode;
  22664. fragmentCode = prefix + fragmentCode;
  22665. // Number lines of shaders source code
  22666. var i = 2;
  22667. var regex = /\n/gm;
  22668. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22669. i = 2;
  22670. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22671. // Dump shaders name and formatted source code
  22672. if (this.name.vertexElement) {
  22673. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22674. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22675. }
  22676. else if (this.name.vertex) {
  22677. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22678. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22679. }
  22680. else {
  22681. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22682. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22683. }
  22684. };
  22685. ;
  22686. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22687. var preparedSourceCode = this._processPrecision(sourceCode);
  22688. if (this._engine.webGLVersion == 1) {
  22689. callback(preparedSourceCode);
  22690. return;
  22691. }
  22692. // Already converted
  22693. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22694. callback(preparedSourceCode.replace("#version 300 es", ""));
  22695. return;
  22696. }
  22697. // Remove extensions
  22698. // #extension GL_OES_standard_derivatives : enable
  22699. // #extension GL_EXT_shader_texture_lod : enable
  22700. // #extension GL_EXT_frag_depth : enable
  22701. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22702. var result = preparedSourceCode.replace(regex, "");
  22703. // Migrate to GLSL v300
  22704. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22705. result = result.replace(/attribute[ \t]/g, "in ");
  22706. result = result.replace(/[ \t]attribute/g, " in");
  22707. if (isFragment) {
  22708. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22709. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22710. result = result.replace(/texture2D\(/g, "texture(");
  22711. result = result.replace(/textureCube\(/g, "texture(");
  22712. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22713. result = result.replace(/gl_FragColor/g, "glFragColor");
  22714. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22715. }
  22716. callback(result);
  22717. };
  22718. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22719. var _this = this;
  22720. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22721. var match = regex.exec(sourceCode);
  22722. var returnValue = new String(sourceCode);
  22723. while (match != null) {
  22724. var includeFile = match[1];
  22725. // Uniform declaration
  22726. if (includeFile.indexOf("__decl__") !== -1) {
  22727. includeFile = includeFile.replace(/__decl__/, "");
  22728. if (this._engine.webGLVersion != 1) {
  22729. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22730. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22731. }
  22732. includeFile = includeFile + "Declaration";
  22733. }
  22734. if (Effect.IncludesShadersStore[includeFile]) {
  22735. // Substitution
  22736. var includeContent = Effect.IncludesShadersStore[includeFile];
  22737. if (match[2]) {
  22738. var splits = match[3].split(",");
  22739. for (var index = 0; index < splits.length; index += 2) {
  22740. var source = new RegExp(splits[index], "g");
  22741. var dest = splits[index + 1];
  22742. includeContent = includeContent.replace(source, dest);
  22743. }
  22744. }
  22745. if (match[4]) {
  22746. var indexString = match[5];
  22747. if (indexString.indexOf("..") !== -1) {
  22748. var indexSplits = indexString.split("..");
  22749. var minIndex = parseInt(indexSplits[0]);
  22750. var maxIndex = parseInt(indexSplits[1]);
  22751. var sourceIncludeContent = includeContent.slice(0);
  22752. includeContent = "";
  22753. if (isNaN(maxIndex)) {
  22754. maxIndex = this._indexParameters[indexSplits[1]];
  22755. }
  22756. for (var i = minIndex; i < maxIndex; i++) {
  22757. if (this._engine.webGLVersion === 1) {
  22758. // Ubo replacement
  22759. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22760. return p1 + "{X}";
  22761. });
  22762. }
  22763. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22764. }
  22765. }
  22766. else {
  22767. if (this._engine.webGLVersion === 1) {
  22768. // Ubo replacement
  22769. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22770. return p1 + "{X}";
  22771. });
  22772. }
  22773. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22774. }
  22775. }
  22776. // Replace
  22777. returnValue = returnValue.replace(match[0], includeContent);
  22778. }
  22779. else {
  22780. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22781. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22782. Effect.IncludesShadersStore[includeFile] = fileContent;
  22783. _this._processIncludes(returnValue, callback);
  22784. });
  22785. return;
  22786. }
  22787. match = regex.exec(sourceCode);
  22788. }
  22789. callback(returnValue);
  22790. };
  22791. Effect.prototype._processPrecision = function (source) {
  22792. if (source.indexOf("precision highp float") === -1) {
  22793. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22794. source = "precision mediump float;\n" + source;
  22795. }
  22796. else {
  22797. source = "precision highp float;\n" + source;
  22798. }
  22799. }
  22800. else {
  22801. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22802. source = source.replace("precision highp float", "precision mediump float");
  22803. }
  22804. }
  22805. return source;
  22806. };
  22807. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22808. try {
  22809. var engine = this._engine;
  22810. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22811. if (engine.webGLVersion > 1) {
  22812. for (var name in this._uniformBuffersNames) {
  22813. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22814. }
  22815. }
  22816. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22817. this._attributes = engine.getAttributes(this._program, attributesNames);
  22818. var index;
  22819. for (index = 0; index < this._samplers.length; index++) {
  22820. var sampler = this.getUniform(this._samplers[index]);
  22821. if (sampler == null) {
  22822. this._samplers.splice(index, 1);
  22823. index--;
  22824. }
  22825. }
  22826. engine.bindSamplers(this);
  22827. this._compilationError = "";
  22828. this._isReady = true;
  22829. if (this.onCompiled) {
  22830. this.onCompiled(this);
  22831. }
  22832. }
  22833. catch (e) {
  22834. this._compilationError = e.message;
  22835. // Let's go through fallbacks then
  22836. BABYLON.Tools.Error("Unable to compile effect:");
  22837. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22838. return " " + uniform;
  22839. }));
  22840. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22841. return " " + attribute;
  22842. }));
  22843. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22844. BABYLON.Tools.Error("Error: " + this._compilationError);
  22845. if (fallbacks && fallbacks.isMoreFallbacks) {
  22846. BABYLON.Tools.Error("Trying next fallback.");
  22847. defines = fallbacks.reduce(defines);
  22848. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22849. }
  22850. else {
  22851. if (this.onError) {
  22852. this.onError(this, this._compilationError);
  22853. }
  22854. }
  22855. }
  22856. };
  22857. Object.defineProperty(Effect.prototype, "isSupported", {
  22858. get: function () {
  22859. return this._compilationError === "";
  22860. },
  22861. enumerable: true,
  22862. configurable: true
  22863. });
  22864. Effect.prototype._bindTexture = function (channel, texture) {
  22865. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22866. };
  22867. Effect.prototype.setTexture = function (channel, texture) {
  22868. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22869. };
  22870. Effect.prototype.setTextureArray = function (channel, textures) {
  22871. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22872. var initialPos = this._samplers.indexOf(channel);
  22873. for (var index = 1; index < textures.length; index++) {
  22874. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22875. }
  22876. }
  22877. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22878. };
  22879. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22880. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22881. };
  22882. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22883. var cache = this._valueCache[uniformName];
  22884. var flag = matrix.updateFlag;
  22885. if (cache !== undefined && cache === flag) {
  22886. return false;
  22887. }
  22888. this._valueCache[uniformName] = flag;
  22889. return true;
  22890. };
  22891. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22892. var cache = this._valueCache[uniformName];
  22893. if (!cache) {
  22894. cache = [x, y];
  22895. this._valueCache[uniformName] = cache;
  22896. return true;
  22897. }
  22898. var changed = false;
  22899. if (cache[0] !== x) {
  22900. cache[0] = x;
  22901. changed = true;
  22902. }
  22903. if (cache[1] !== y) {
  22904. cache[1] = y;
  22905. changed = true;
  22906. }
  22907. return changed;
  22908. };
  22909. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22910. var cache = this._valueCache[uniformName];
  22911. if (!cache) {
  22912. cache = [x, y, z];
  22913. this._valueCache[uniformName] = cache;
  22914. return true;
  22915. }
  22916. var changed = false;
  22917. if (cache[0] !== x) {
  22918. cache[0] = x;
  22919. changed = true;
  22920. }
  22921. if (cache[1] !== y) {
  22922. cache[1] = y;
  22923. changed = true;
  22924. }
  22925. if (cache[2] !== z) {
  22926. cache[2] = z;
  22927. changed = true;
  22928. }
  22929. return changed;
  22930. };
  22931. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22932. var cache = this._valueCache[uniformName];
  22933. if (!cache) {
  22934. cache = [x, y, z, w];
  22935. this._valueCache[uniformName] = cache;
  22936. return true;
  22937. }
  22938. var changed = false;
  22939. if (cache[0] !== x) {
  22940. cache[0] = x;
  22941. changed = true;
  22942. }
  22943. if (cache[1] !== y) {
  22944. cache[1] = y;
  22945. changed = true;
  22946. }
  22947. if (cache[2] !== z) {
  22948. cache[2] = z;
  22949. changed = true;
  22950. }
  22951. if (cache[3] !== w) {
  22952. cache[3] = w;
  22953. changed = true;
  22954. }
  22955. return changed;
  22956. };
  22957. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22958. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22959. return;
  22960. }
  22961. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22962. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22963. };
  22964. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22965. this._engine.bindUniformBlock(this._program, blockName, index);
  22966. };
  22967. Effect.prototype.setIntArray = function (uniformName, array) {
  22968. this._valueCache[uniformName] = null;
  22969. this._engine.setIntArray(this.getUniform(uniformName), array);
  22970. return this;
  22971. };
  22972. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22973. this._valueCache[uniformName] = null;
  22974. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22975. return this;
  22976. };
  22977. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22978. this._valueCache[uniformName] = null;
  22979. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22980. return this;
  22981. };
  22982. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22983. this._valueCache[uniformName] = null;
  22984. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22985. return this;
  22986. };
  22987. Effect.prototype.setFloatArray = function (uniformName, array) {
  22988. this._valueCache[uniformName] = null;
  22989. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22990. return this;
  22991. };
  22992. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22993. this._valueCache[uniformName] = null;
  22994. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22995. return this;
  22996. };
  22997. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22998. this._valueCache[uniformName] = null;
  22999. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23000. return this;
  23001. };
  23002. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23003. this._valueCache[uniformName] = null;
  23004. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23005. return this;
  23006. };
  23007. Effect.prototype.setArray = function (uniformName, array) {
  23008. this._valueCache[uniformName] = null;
  23009. this._engine.setArray(this.getUniform(uniformName), array);
  23010. return this;
  23011. };
  23012. Effect.prototype.setArray2 = function (uniformName, array) {
  23013. this._valueCache[uniformName] = null;
  23014. this._engine.setArray2(this.getUniform(uniformName), array);
  23015. return this;
  23016. };
  23017. Effect.prototype.setArray3 = function (uniformName, array) {
  23018. this._valueCache[uniformName] = null;
  23019. this._engine.setArray3(this.getUniform(uniformName), array);
  23020. return this;
  23021. };
  23022. Effect.prototype.setArray4 = function (uniformName, array) {
  23023. this._valueCache[uniformName] = null;
  23024. this._engine.setArray4(this.getUniform(uniformName), array);
  23025. return this;
  23026. };
  23027. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23028. if (!matrices) {
  23029. return;
  23030. }
  23031. this._valueCache[uniformName] = null;
  23032. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23033. return this;
  23034. };
  23035. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23036. if (this._cacheMatrix(uniformName, matrix)) {
  23037. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23038. }
  23039. return this;
  23040. };
  23041. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23042. this._valueCache[uniformName] = null;
  23043. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23044. return this;
  23045. };
  23046. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23047. this._valueCache[uniformName] = null;
  23048. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23049. return this;
  23050. };
  23051. Effect.prototype.setFloat = function (uniformName, value) {
  23052. var cache = this._valueCache[uniformName];
  23053. if (cache !== undefined && cache === value)
  23054. return this;
  23055. this._valueCache[uniformName] = value;
  23056. this._engine.setFloat(this.getUniform(uniformName), value);
  23057. return this;
  23058. };
  23059. Effect.prototype.setBool = function (uniformName, bool) {
  23060. var cache = this._valueCache[uniformName];
  23061. if (cache !== undefined && cache === bool)
  23062. return this;
  23063. this._valueCache[uniformName] = bool;
  23064. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23065. return this;
  23066. };
  23067. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23068. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23069. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23070. }
  23071. return this;
  23072. };
  23073. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23074. if (this._cacheFloat2(uniformName, x, y)) {
  23075. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23076. }
  23077. return this;
  23078. };
  23079. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23080. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23081. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23082. }
  23083. return this;
  23084. };
  23085. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23086. if (this._cacheFloat3(uniformName, x, y, z)) {
  23087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23088. }
  23089. return this;
  23090. };
  23091. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23092. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23093. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23094. }
  23095. return this;
  23096. };
  23097. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23098. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23099. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23100. }
  23101. return this;
  23102. };
  23103. Effect.prototype.setColor3 = function (uniformName, color3) {
  23104. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23105. this._engine.setColor3(this.getUniform(uniformName), color3);
  23106. }
  23107. return this;
  23108. };
  23109. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23110. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23111. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23112. }
  23113. return this;
  23114. };
  23115. Effect.prototype._recombineShader = function (node) {
  23116. if (node.define) {
  23117. if (node.condition) {
  23118. var defineIndex = this.defines.indexOf("#define " + node.define);
  23119. if (defineIndex === -1) {
  23120. return null;
  23121. }
  23122. var nextComma = this.defines.indexOf("\n", defineIndex);
  23123. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23124. var condition = defineValue + node.condition;
  23125. if (!eval(condition)) {
  23126. return null;
  23127. }
  23128. }
  23129. else if (node.ndef) {
  23130. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23131. return null;
  23132. }
  23133. }
  23134. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23135. return null;
  23136. }
  23137. }
  23138. var result = "";
  23139. for (var index = 0; index < node.children.length; index++) {
  23140. var line = node.children[index];
  23141. if (line.children) {
  23142. var combined = this._recombineShader(line);
  23143. if (combined !== null) {
  23144. result += combined + "\r\n";
  23145. }
  23146. continue;
  23147. }
  23148. if (line.length > 0) {
  23149. result += line + "\r\n";
  23150. }
  23151. }
  23152. return result;
  23153. };
  23154. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23155. var root = {
  23156. children: []
  23157. };
  23158. var currentNode = root;
  23159. var lines = shaderString.split("\n");
  23160. for (var index = 0; index < lines.length; index++) {
  23161. var line = lines[index].trim();
  23162. // #ifdef
  23163. var pos = line.indexOf("#ifdef ");
  23164. if (pos !== -1) {
  23165. var define = line.substr(pos + 7);
  23166. var newNode = {
  23167. condition: null,
  23168. ndef: false,
  23169. define: define,
  23170. children: [],
  23171. parent: currentNode
  23172. };
  23173. currentNode.children.push(newNode);
  23174. currentNode = newNode;
  23175. continue;
  23176. }
  23177. // #ifndef
  23178. var pos = line.indexOf("#ifndef ");
  23179. if (pos !== -1) {
  23180. var define = line.substr(pos + 8);
  23181. newNode = {
  23182. condition: null,
  23183. define: define,
  23184. ndef: true,
  23185. children: [],
  23186. parent: currentNode
  23187. };
  23188. currentNode.children.push(newNode);
  23189. currentNode = newNode;
  23190. continue;
  23191. }
  23192. // #if
  23193. var pos = line.indexOf("#if ");
  23194. if (pos !== -1) {
  23195. var define = line.substr(pos + 4).trim();
  23196. var conditionPos = define.indexOf(" ");
  23197. newNode = {
  23198. condition: define.substr(conditionPos + 1),
  23199. define: define.substr(0, conditionPos),
  23200. ndef: false,
  23201. children: [],
  23202. parent: currentNode
  23203. };
  23204. currentNode.children.push(newNode);
  23205. currentNode = newNode;
  23206. continue;
  23207. }
  23208. // #endif
  23209. pos = line.indexOf("#endif");
  23210. if (pos !== -1) {
  23211. currentNode = currentNode.parent;
  23212. continue;
  23213. }
  23214. currentNode.children.push(line);
  23215. }
  23216. // Recombine
  23217. return this._recombineShader(root);
  23218. };
  23219. return Effect;
  23220. }());
  23221. Effect._uniqueIdSeed = 0;
  23222. Effect._baseCache = {};
  23223. // Statics
  23224. Effect.ShadersStore = {};
  23225. Effect.IncludesShadersStore = {};
  23226. BABYLON.Effect = Effect;
  23227. })(BABYLON || (BABYLON = {}));
  23228. //# sourceMappingURL=babylon.effect.js.map
  23229. var BABYLON;
  23230. (function (BABYLON) {
  23231. var MaterialHelper = (function () {
  23232. function MaterialHelper() {
  23233. }
  23234. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23235. if (defines._areMiscDirty) {
  23236. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23237. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23238. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23239. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23240. }
  23241. };
  23242. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23243. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23244. var changed = false;
  23245. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23246. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23247. changed = true;
  23248. }
  23249. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23250. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23251. changed = true;
  23252. }
  23253. if (defines["INSTANCES"] !== useInstances) {
  23254. defines["INSTANCES"] = useInstances;
  23255. changed = true;
  23256. }
  23257. if (changed) {
  23258. defines.markAsUnprocessed();
  23259. }
  23260. };
  23261. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23262. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23263. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23264. return false;
  23265. }
  23266. defines._normals = defines._needNormals;
  23267. defines._uvs = defines._needUVs;
  23268. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23269. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23270. defines["TANGENT"] = true;
  23271. }
  23272. if (defines._needUVs) {
  23273. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23274. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23275. }
  23276. else {
  23277. defines["UV1"] = false;
  23278. defines["UV2"] = false;
  23279. }
  23280. if (useVertexColor) {
  23281. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23282. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23283. }
  23284. if (useBones) {
  23285. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23286. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23287. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23288. }
  23289. else {
  23290. defines["NUM_BONE_INFLUENCERS"] = 0;
  23291. defines["BonesPerMesh"] = 0;
  23292. }
  23293. }
  23294. if (useMorphTargets) {
  23295. if (mesh.morphTargetManager) {
  23296. var manager = mesh.morphTargetManager;
  23297. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23298. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23299. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23300. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23301. }
  23302. else {
  23303. defines["MORPHTARGETS_TANGENT"] = false;
  23304. defines["MORPHTARGETS_NORMAL"] = false;
  23305. defines["MORPHTARGETS"] = false;
  23306. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23307. }
  23308. }
  23309. return true;
  23310. };
  23311. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23312. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23313. if (disableLighting === void 0) { disableLighting = false; }
  23314. if (!defines._areLightsDirty) {
  23315. return defines._needNormals;
  23316. }
  23317. var lightIndex = 0;
  23318. var needNormals = false;
  23319. var needRebuild = false;
  23320. var lightmapMode = false;
  23321. var shadowEnabled = false;
  23322. var specularEnabled = false;
  23323. if (scene.lightsEnabled && !disableLighting) {
  23324. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23325. var light = _a[_i];
  23326. needNormals = true;
  23327. if (defines["LIGHT" + lightIndex] === undefined) {
  23328. needRebuild = true;
  23329. }
  23330. defines["LIGHT" + lightIndex] = true;
  23331. defines["SPOTLIGHT" + lightIndex] = false;
  23332. defines["HEMILIGHT" + lightIndex] = false;
  23333. defines["POINTLIGHT" + lightIndex] = false;
  23334. defines["DIRLIGHT" + lightIndex] = false;
  23335. var type;
  23336. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23337. type = "SPOTLIGHT" + lightIndex;
  23338. }
  23339. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23340. type = "HEMILIGHT" + lightIndex;
  23341. }
  23342. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23343. type = "POINTLIGHT" + lightIndex;
  23344. }
  23345. else {
  23346. type = "DIRLIGHT" + lightIndex;
  23347. }
  23348. defines[type] = true;
  23349. // Specular
  23350. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23351. specularEnabled = true;
  23352. }
  23353. // Shadows
  23354. defines["SHADOW" + lightIndex] = false;
  23355. defines["SHADOWPCF" + lightIndex] = false;
  23356. defines["SHADOWESM" + lightIndex] = false;
  23357. defines["SHADOWCUBE" + lightIndex] = false;
  23358. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23359. var shadowGenerator = light.getShadowGenerator();
  23360. if (shadowGenerator) {
  23361. shadowEnabled = true;
  23362. shadowGenerator.prepareDefines(defines, lightIndex);
  23363. }
  23364. }
  23365. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23366. lightmapMode = true;
  23367. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23368. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23369. }
  23370. else {
  23371. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23372. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23373. }
  23374. lightIndex++;
  23375. if (lightIndex === maxSimultaneousLights)
  23376. break;
  23377. }
  23378. }
  23379. defines["SPECULARTERM"] = specularEnabled;
  23380. defines["SHADOWS"] = shadowEnabled;
  23381. // Resetting all other lights if any
  23382. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23383. if (defines["LIGHT" + index] !== undefined) {
  23384. defines["LIGHT" + index] = false;
  23385. }
  23386. }
  23387. var caps = scene.getEngine().getCaps();
  23388. if (defines["SHADOWFLOAT"] === undefined) {
  23389. needRebuild = true;
  23390. }
  23391. defines["SHADOWFLOAT"] = shadowEnabled &&
  23392. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23393. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23394. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23395. if (needRebuild) {
  23396. defines.rebuild();
  23397. }
  23398. return needNormals;
  23399. };
  23400. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23401. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23402. var uniformsList, uniformBuffersList, samplersList, defines;
  23403. if (uniformsListOrOptions.uniformsNames) {
  23404. var options = uniformsListOrOptions;
  23405. uniformsList = options.uniformsNames;
  23406. uniformBuffersList = options.uniformBuffersNames;
  23407. samplersList = options.samplers;
  23408. defines = options.defines;
  23409. maxSimultaneousLights = options.maxSimultaneousLights;
  23410. }
  23411. else {
  23412. uniformsList = uniformsListOrOptions;
  23413. }
  23414. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23415. if (!defines["LIGHT" + lightIndex]) {
  23416. break;
  23417. }
  23418. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23419. if (uniformBuffersList) {
  23420. uniformBuffersList.push("Light" + lightIndex);
  23421. }
  23422. samplersList.push("shadowSampler" + lightIndex);
  23423. }
  23424. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23425. uniformsList.push("morphTargetInfluences");
  23426. }
  23427. };
  23428. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23429. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23430. if (!defines["SHADOWS"]) {
  23431. return;
  23432. }
  23433. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23434. if (!defines["LIGHT" + lightIndex]) {
  23435. break;
  23436. }
  23437. if (lightIndex > 0) {
  23438. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23439. }
  23440. if (defines["SHADOW" + lightIndex]) {
  23441. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23442. }
  23443. if (defines["SHADOWPCF" + lightIndex]) {
  23444. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23445. }
  23446. if (defines["SHADOWESM" + lightIndex]) {
  23447. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23448. }
  23449. }
  23450. };
  23451. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23452. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23453. if (influencers > 0) {
  23454. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23455. var manager = mesh.morphTargetManager;
  23456. var normal = manager.supportsNormals && defines["NORMAL"];
  23457. var tangent = manager.supportsTangents && defines["TANGENT"];
  23458. for (var index = 0; index < influencers; index++) {
  23459. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23460. if (normal) {
  23461. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23462. }
  23463. if (tangent) {
  23464. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23465. }
  23466. if (attribs.length > maxAttributesCount) {
  23467. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23468. }
  23469. }
  23470. }
  23471. };
  23472. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23473. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23474. fallbacks.addCPUSkinningFallback(0, mesh);
  23475. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23476. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23477. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23480. }
  23481. }
  23482. };
  23483. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23484. if (defines["INSTANCES"]) {
  23485. attribs.push("world0");
  23486. attribs.push("world1");
  23487. attribs.push("world2");
  23488. attribs.push("world3");
  23489. }
  23490. };
  23491. // Bindings
  23492. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23493. if (light.shadowEnabled && mesh.receiveShadows) {
  23494. var shadowGenerator = light.getShadowGenerator();
  23495. if (shadowGenerator) {
  23496. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23497. }
  23498. }
  23499. return depthValuesAlreadySet;
  23500. };
  23501. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23502. light.transferToEffect(effect, lightIndex + "");
  23503. };
  23504. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23505. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23506. var lightIndex = 0;
  23507. var depthValuesAlreadySet = false;
  23508. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23509. var light = _a[_i];
  23510. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23511. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23512. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23513. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23514. if (defines["SPECULARTERM"]) {
  23515. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23516. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23517. }
  23518. // Shadows
  23519. if (scene.shadowsEnabled) {
  23520. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23521. }
  23522. light._uniformBuffer.update();
  23523. lightIndex++;
  23524. if (lightIndex === maxSimultaneousLights)
  23525. break;
  23526. }
  23527. };
  23528. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23529. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23530. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23531. effect.setColor3("vFogColor", scene.fogColor);
  23532. }
  23533. };
  23534. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23535. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23536. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23537. if (matrices) {
  23538. effect.setMatrices("mBones", matrices);
  23539. }
  23540. }
  23541. };
  23542. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23543. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23544. return;
  23545. }
  23546. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23547. };
  23548. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23549. if (defines["LOGARITHMICDEPTH"]) {
  23550. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23551. }
  23552. };
  23553. MaterialHelper.BindClipPlane = function (effect, scene) {
  23554. if (scene.clipPlane) {
  23555. var clipPlane = scene.clipPlane;
  23556. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23557. }
  23558. };
  23559. return MaterialHelper;
  23560. }());
  23561. BABYLON.MaterialHelper = MaterialHelper;
  23562. })(BABYLON || (BABYLON = {}));
  23563. //# sourceMappingURL=babylon.materialHelper.js.map
  23564. var BABYLON;
  23565. (function (BABYLON) {
  23566. var MaterialDefines = (function () {
  23567. function MaterialDefines() {
  23568. this._isDirty = true;
  23569. this._areLightsDirty = true;
  23570. this._areAttributesDirty = true;
  23571. this._areTexturesDirty = true;
  23572. this._areFresnelDirty = true;
  23573. this._areMiscDirty = true;
  23574. this._normals = false;
  23575. this._uvs = false;
  23576. this._needNormals = false;
  23577. this._needUVs = false;
  23578. }
  23579. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23580. get: function () {
  23581. return this._isDirty;
  23582. },
  23583. enumerable: true,
  23584. configurable: true
  23585. });
  23586. MaterialDefines.prototype.markAsProcessed = function () {
  23587. this._isDirty = false;
  23588. this._areAttributesDirty = false;
  23589. this._areTexturesDirty = false;
  23590. this._areFresnelDirty = false;
  23591. this._areLightsDirty = false;
  23592. this._areMiscDirty = false;
  23593. };
  23594. MaterialDefines.prototype.markAsUnprocessed = function () {
  23595. this._isDirty = true;
  23596. };
  23597. MaterialDefines.prototype.markAllAsDirty = function () {
  23598. this._areTexturesDirty = true;
  23599. this._areAttributesDirty = true;
  23600. this._areLightsDirty = true;
  23601. this._areFresnelDirty = true;
  23602. this._areMiscDirty = true;
  23603. this._isDirty = true;
  23604. };
  23605. MaterialDefines.prototype.markAsLightDirty = function () {
  23606. this._areLightsDirty = true;
  23607. this._isDirty = true;
  23608. };
  23609. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23610. this._areAttributesDirty = true;
  23611. this._isDirty = true;
  23612. };
  23613. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23614. this._areTexturesDirty = true;
  23615. this._isDirty = true;
  23616. };
  23617. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23618. this._areFresnelDirty = true;
  23619. this._isDirty = true;
  23620. };
  23621. MaterialDefines.prototype.markAsMiscDirty = function () {
  23622. this._areMiscDirty = true;
  23623. this._isDirty = true;
  23624. };
  23625. MaterialDefines.prototype.rebuild = function () {
  23626. if (this._keys) {
  23627. delete this._keys;
  23628. }
  23629. this._keys = [];
  23630. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23631. var key = _a[_i];
  23632. if (key[0] === "_") {
  23633. continue;
  23634. }
  23635. this._keys.push(key);
  23636. }
  23637. };
  23638. MaterialDefines.prototype.isEqual = function (other) {
  23639. if (this._keys.length !== other._keys.length) {
  23640. return false;
  23641. }
  23642. for (var index = 0; index < this._keys.length; index++) {
  23643. var prop = this._keys[index];
  23644. if (this[prop] !== other[prop]) {
  23645. return false;
  23646. }
  23647. }
  23648. return true;
  23649. };
  23650. MaterialDefines.prototype.cloneTo = function (other) {
  23651. if (this._keys.length !== other._keys.length) {
  23652. other._keys = this._keys.slice(0);
  23653. }
  23654. for (var index = 0; index < this._keys.length; index++) {
  23655. var prop = this._keys[index];
  23656. other[prop] = this[prop];
  23657. }
  23658. };
  23659. MaterialDefines.prototype.reset = function () {
  23660. for (var index = 0; index < this._keys.length; index++) {
  23661. var prop = this._keys[index];
  23662. if (typeof (this[prop]) === "number") {
  23663. this[prop] = 0;
  23664. }
  23665. else {
  23666. this[prop] = false;
  23667. }
  23668. }
  23669. };
  23670. MaterialDefines.prototype.toString = function () {
  23671. var result = "";
  23672. for (var index = 0; index < this._keys.length; index++) {
  23673. var prop = this._keys[index];
  23674. var value = this[prop];
  23675. if (typeof (value) === "number") {
  23676. result += "#define " + prop + " " + this[prop] + "\n";
  23677. }
  23678. else if (value) {
  23679. result += "#define " + prop + "\n";
  23680. }
  23681. }
  23682. return result;
  23683. };
  23684. return MaterialDefines;
  23685. }());
  23686. BABYLON.MaterialDefines = MaterialDefines;
  23687. var Material = (function () {
  23688. function Material(name, scene, doNotAdd) {
  23689. this.checkReadyOnEveryCall = false;
  23690. this.checkReadyOnlyOnce = false;
  23691. this.state = "";
  23692. this.alpha = 1.0;
  23693. this._backFaceCulling = true;
  23694. this.doNotSerialize = false;
  23695. this.storeEffectOnSubMeshes = false;
  23696. /**
  23697. * An event triggered when the material is disposed.
  23698. * @type {BABYLON.Observable}
  23699. */
  23700. this.onDisposeObservable = new BABYLON.Observable();
  23701. /**
  23702. * An event triggered when the material is bound.
  23703. * @type {BABYLON.Observable}
  23704. */
  23705. this.onBindObservable = new BABYLON.Observable();
  23706. /**
  23707. * An event triggered when the material is unbound.
  23708. * @type {BABYLON.Observable}
  23709. */
  23710. this.onUnBindObservable = new BABYLON.Observable();
  23711. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23712. this.disableDepthWrite = false;
  23713. this._fogEnabled = true;
  23714. this.pointSize = 1.0;
  23715. this.zOffset = 0;
  23716. this._wasPreviouslyReady = false;
  23717. this._fillMode = Material.TriangleFillMode;
  23718. this.name = name;
  23719. this.id = name;
  23720. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23721. if (this._scene.useRightHandedSystem) {
  23722. this.sideOrientation = Material.ClockWiseSideOrientation;
  23723. }
  23724. else {
  23725. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23726. }
  23727. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23728. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23729. if (!doNotAdd) {
  23730. this._scene.materials.push(this);
  23731. }
  23732. }
  23733. Object.defineProperty(Material, "TriangleFillMode", {
  23734. get: function () {
  23735. return Material._TriangleFillMode;
  23736. },
  23737. enumerable: true,
  23738. configurable: true
  23739. });
  23740. Object.defineProperty(Material, "WireFrameFillMode", {
  23741. get: function () {
  23742. return Material._WireFrameFillMode;
  23743. },
  23744. enumerable: true,
  23745. configurable: true
  23746. });
  23747. Object.defineProperty(Material, "PointFillMode", {
  23748. get: function () {
  23749. return Material._PointFillMode;
  23750. },
  23751. enumerable: true,
  23752. configurable: true
  23753. });
  23754. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23755. get: function () {
  23756. return Material._ClockWiseSideOrientation;
  23757. },
  23758. enumerable: true,
  23759. configurable: true
  23760. });
  23761. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23762. get: function () {
  23763. return Material._CounterClockWiseSideOrientation;
  23764. },
  23765. enumerable: true,
  23766. configurable: true
  23767. });
  23768. Object.defineProperty(Material, "TextureDirtyFlag", {
  23769. get: function () {
  23770. return Material._TextureDirtyFlag;
  23771. },
  23772. enumerable: true,
  23773. configurable: true
  23774. });
  23775. Object.defineProperty(Material, "LightDirtyFlag", {
  23776. get: function () {
  23777. return Material._LightDirtyFlag;
  23778. },
  23779. enumerable: true,
  23780. configurable: true
  23781. });
  23782. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23783. get: function () {
  23784. return Material._FresnelDirtyFlag;
  23785. },
  23786. enumerable: true,
  23787. configurable: true
  23788. });
  23789. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23790. get: function () {
  23791. return Material._AttributesDirtyFlag;
  23792. },
  23793. enumerable: true,
  23794. configurable: true
  23795. });
  23796. Object.defineProperty(Material, "MiscDirtyFlag", {
  23797. get: function () {
  23798. return Material._MiscDirtyFlag;
  23799. },
  23800. enumerable: true,
  23801. configurable: true
  23802. });
  23803. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23804. get: function () {
  23805. return this._backFaceCulling;
  23806. },
  23807. set: function (value) {
  23808. if (this._backFaceCulling === value) {
  23809. return;
  23810. }
  23811. this._backFaceCulling = value;
  23812. this.markAsDirty(Material.TextureDirtyFlag);
  23813. },
  23814. enumerable: true,
  23815. configurable: true
  23816. });
  23817. Object.defineProperty(Material.prototype, "onDispose", {
  23818. set: function (callback) {
  23819. if (this._onDisposeObserver) {
  23820. this.onDisposeObservable.remove(this._onDisposeObserver);
  23821. }
  23822. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23823. },
  23824. enumerable: true,
  23825. configurable: true
  23826. });
  23827. Object.defineProperty(Material.prototype, "onBind", {
  23828. set: function (callback) {
  23829. if (this._onBindObserver) {
  23830. this.onBindObservable.remove(this._onBindObserver);
  23831. }
  23832. this._onBindObserver = this.onBindObservable.add(callback);
  23833. },
  23834. enumerable: true,
  23835. configurable: true
  23836. });
  23837. Object.defineProperty(Material.prototype, "fogEnabled", {
  23838. get: function () {
  23839. return this._fogEnabled;
  23840. },
  23841. set: function (value) {
  23842. if (this._fogEnabled === value) {
  23843. return;
  23844. }
  23845. this._fogEnabled = value;
  23846. this.markAsDirty(Material.MiscDirtyFlag);
  23847. },
  23848. enumerable: true,
  23849. configurable: true
  23850. });
  23851. Object.defineProperty(Material.prototype, "wireframe", {
  23852. get: function () {
  23853. return this._fillMode === Material.WireFrameFillMode;
  23854. },
  23855. set: function (value) {
  23856. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23857. },
  23858. enumerable: true,
  23859. configurable: true
  23860. });
  23861. Object.defineProperty(Material.prototype, "pointsCloud", {
  23862. get: function () {
  23863. return this._fillMode === Material.PointFillMode;
  23864. },
  23865. set: function (value) {
  23866. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. Object.defineProperty(Material.prototype, "fillMode", {
  23872. get: function () {
  23873. return this._fillMode;
  23874. },
  23875. set: function (value) {
  23876. if (this._fillMode === value) {
  23877. return;
  23878. }
  23879. this._fillMode = value;
  23880. this.markAsDirty(Material.MiscDirtyFlag);
  23881. },
  23882. enumerable: true,
  23883. configurable: true
  23884. });
  23885. /**
  23886. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23887. * subclasses should override adding information pertainent to themselves
  23888. */
  23889. Material.prototype.toString = function (fullDetails) {
  23890. var ret = "Name: " + this.name;
  23891. if (fullDetails) {
  23892. }
  23893. return ret;
  23894. };
  23895. /**
  23896. * Child classes can use it to update shaders
  23897. */
  23898. Material.prototype.markAsDirty = function (flag) {
  23899. };
  23900. Material.prototype.getClassName = function () {
  23901. return "Material";
  23902. };
  23903. Object.defineProperty(Material.prototype, "isFrozen", {
  23904. get: function () {
  23905. return this.checkReadyOnlyOnce;
  23906. },
  23907. enumerable: true,
  23908. configurable: true
  23909. });
  23910. Material.prototype.freeze = function () {
  23911. this.checkReadyOnlyOnce = true;
  23912. };
  23913. Material.prototype.unfreeze = function () {
  23914. this.checkReadyOnlyOnce = false;
  23915. };
  23916. Material.prototype.isReady = function (mesh, useInstances) {
  23917. return true;
  23918. };
  23919. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23920. return false;
  23921. };
  23922. Material.prototype.getEffect = function () {
  23923. return this._effect;
  23924. };
  23925. Material.prototype.getScene = function () {
  23926. return this._scene;
  23927. };
  23928. Material.prototype.needAlphaBlending = function () {
  23929. return (this.alpha < 1.0);
  23930. };
  23931. Material.prototype.needAlphaTesting = function () {
  23932. return false;
  23933. };
  23934. Material.prototype.getAlphaTestTexture = function () {
  23935. return null;
  23936. };
  23937. Material.prototype.markDirty = function () {
  23938. this._wasPreviouslyReady = false;
  23939. };
  23940. Material.prototype._preBind = function (effect) {
  23941. var engine = this._scene.getEngine();
  23942. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23943. engine.enableEffect(effect ? effect : this._effect);
  23944. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23945. };
  23946. Material.prototype.bind = function (world, mesh) {
  23947. };
  23948. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23949. };
  23950. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23951. };
  23952. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23953. sceneUbo.bindToEffect(effect, "Scene");
  23954. };
  23955. Material.prototype.bindView = function (effect) {
  23956. if (!this._useUBO) {
  23957. effect.setMatrix("view", this.getScene().getViewMatrix());
  23958. }
  23959. else {
  23960. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23961. }
  23962. };
  23963. Material.prototype.bindViewProjection = function (effect) {
  23964. if (!this._useUBO) {
  23965. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23966. }
  23967. else {
  23968. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23969. }
  23970. };
  23971. Material.prototype._afterBind = function (mesh) {
  23972. this._scene._cachedMaterial = this;
  23973. this.onBindObservable.notifyObservers(mesh);
  23974. if (this.disableDepthWrite) {
  23975. var engine = this._scene.getEngine();
  23976. this._cachedDepthWriteState = engine.getDepthWrite();
  23977. engine.setDepthWrite(false);
  23978. }
  23979. };
  23980. Material.prototype.unbind = function () {
  23981. this.onUnBindObservable.notifyObservers(this);
  23982. if (this.disableDepthWrite) {
  23983. var engine = this._scene.getEngine();
  23984. engine.setDepthWrite(this._cachedDepthWriteState);
  23985. }
  23986. };
  23987. Material.prototype.clone = function (name) {
  23988. return null;
  23989. };
  23990. Material.prototype.getBindedMeshes = function () {
  23991. var result = new Array();
  23992. for (var index = 0; index < this._scene.meshes.length; index++) {
  23993. var mesh = this._scene.meshes[index];
  23994. if (mesh.material === this) {
  23995. result.push(mesh);
  23996. }
  23997. }
  23998. return result;
  23999. };
  24000. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24001. // Animations
  24002. this.getScene().stopAnimation(this);
  24003. // Remove from scene
  24004. var index = this._scene.materials.indexOf(this);
  24005. if (index >= 0) {
  24006. this._scene.materials.splice(index, 1);
  24007. }
  24008. // Remove from meshes
  24009. for (index = 0; index < this._scene.meshes.length; index++) {
  24010. var mesh = this._scene.meshes[index];
  24011. if (mesh.material === this) {
  24012. mesh.material = null;
  24013. if (mesh.geometry) {
  24014. var geometry = mesh.geometry;
  24015. if (this.storeEffectOnSubMeshes) {
  24016. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24017. var subMesh = _a[_i];
  24018. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24019. }
  24020. }
  24021. else {
  24022. geometry._releaseVertexArrayObject(this._effect);
  24023. }
  24024. }
  24025. }
  24026. }
  24027. this._uniformBuffer.dispose();
  24028. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24029. if (forceDisposeEffect && this._effect) {
  24030. if (this.storeEffectOnSubMeshes) {
  24031. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24032. var subMesh = _c[_b];
  24033. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24034. }
  24035. }
  24036. else {
  24037. this._scene.getEngine()._releaseEffect(this._effect);
  24038. }
  24039. this._effect = null;
  24040. }
  24041. // Callback
  24042. this.onDisposeObservable.notifyObservers(this);
  24043. this.onDisposeObservable.clear();
  24044. this.onBindObservable.clear();
  24045. this.onUnBindObservable.clear();
  24046. };
  24047. Material.prototype.serialize = function () {
  24048. return BABYLON.SerializationHelper.Serialize(this);
  24049. };
  24050. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24051. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24052. multiMaterial.id = parsedMultiMaterial.id;
  24053. if (BABYLON.Tags) {
  24054. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24055. }
  24056. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24057. var subMatId = parsedMultiMaterial.materials[matIndex];
  24058. if (subMatId) {
  24059. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24060. }
  24061. else {
  24062. multiMaterial.subMaterials.push(null);
  24063. }
  24064. }
  24065. return multiMaterial;
  24066. };
  24067. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24068. if (!parsedMaterial.customType) {
  24069. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24070. }
  24071. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  24072. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24073. if (!BABYLON.LegacyPBRMaterial) {
  24074. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24075. return;
  24076. }
  24077. }
  24078. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24079. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24080. ;
  24081. };
  24082. return Material;
  24083. }());
  24084. Material._TriangleFillMode = 0;
  24085. Material._WireFrameFillMode = 1;
  24086. Material._PointFillMode = 2;
  24087. Material._ClockWiseSideOrientation = 0;
  24088. Material._CounterClockWiseSideOrientation = 1;
  24089. Material._TextureDirtyFlag = 1;
  24090. Material._LightDirtyFlag = 2;
  24091. Material._FresnelDirtyFlag = 4;
  24092. Material._AttributesDirtyFlag = 8;
  24093. Material._MiscDirtyFlag = 16;
  24094. __decorate([
  24095. BABYLON.serialize()
  24096. ], Material.prototype, "id", void 0);
  24097. __decorate([
  24098. BABYLON.serialize()
  24099. ], Material.prototype, "name", void 0);
  24100. __decorate([
  24101. BABYLON.serialize()
  24102. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24103. __decorate([
  24104. BABYLON.serialize()
  24105. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24106. __decorate([
  24107. BABYLON.serialize()
  24108. ], Material.prototype, "state", void 0);
  24109. __decorate([
  24110. BABYLON.serialize()
  24111. ], Material.prototype, "alpha", void 0);
  24112. __decorate([
  24113. BABYLON.serialize("backFaceCulling")
  24114. ], Material.prototype, "_backFaceCulling", void 0);
  24115. __decorate([
  24116. BABYLON.serialize()
  24117. ], Material.prototype, "sideOrientation", void 0);
  24118. __decorate([
  24119. BABYLON.serialize()
  24120. ], Material.prototype, "alphaMode", void 0);
  24121. __decorate([
  24122. BABYLON.serialize()
  24123. ], Material.prototype, "disableDepthWrite", void 0);
  24124. __decorate([
  24125. BABYLON.serialize("fogEnabled")
  24126. ], Material.prototype, "_fogEnabled", void 0);
  24127. __decorate([
  24128. BABYLON.serialize()
  24129. ], Material.prototype, "pointSize", void 0);
  24130. __decorate([
  24131. BABYLON.serialize()
  24132. ], Material.prototype, "zOffset", void 0);
  24133. __decorate([
  24134. BABYLON.serialize()
  24135. ], Material.prototype, "wireframe", null);
  24136. __decorate([
  24137. BABYLON.serialize()
  24138. ], Material.prototype, "pointsCloud", null);
  24139. __decorate([
  24140. BABYLON.serialize()
  24141. ], Material.prototype, "fillMode", null);
  24142. BABYLON.Material = Material;
  24143. })(BABYLON || (BABYLON = {}));
  24144. //# sourceMappingURL=babylon.material.js.map
  24145. var BABYLON;
  24146. (function (BABYLON) {
  24147. var UniformBuffer = (function () {
  24148. /**
  24149. * Uniform buffer objects.
  24150. *
  24151. * Handles blocks of uniform on the GPU.
  24152. *
  24153. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24154. *
  24155. * For more information, please refer to :
  24156. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24157. */
  24158. function UniformBuffer(engine, data, dynamic) {
  24159. this._engine = engine;
  24160. this._noUBO = engine.webGLVersion === 1;
  24161. this._dynamic = dynamic;
  24162. this._data = data || [];
  24163. this._uniformLocations = {};
  24164. this._uniformSizes = {};
  24165. this._uniformLocationPointer = 0;
  24166. this._needSync = false;
  24167. if (this._noUBO) {
  24168. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24169. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24170. this.updateFloat = this._updateFloatForEffect;
  24171. this.updateFloat2 = this._updateFloat2ForEffect;
  24172. this.updateFloat3 = this._updateFloat3ForEffect;
  24173. this.updateFloat4 = this._updateFloat4ForEffect;
  24174. this.updateMatrix = this._updateMatrixForEffect;
  24175. this.updateVector3 = this._updateVector3ForEffect;
  24176. this.updateVector4 = this._updateVector4ForEffect;
  24177. this.updateColor3 = this._updateColor3ForEffect;
  24178. this.updateColor4 = this._updateColor4ForEffect;
  24179. }
  24180. else {
  24181. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24182. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24183. this.updateFloat = this._updateFloatForUniform;
  24184. this.updateFloat2 = this._updateFloat2ForUniform;
  24185. this.updateFloat3 = this._updateFloat3ForUniform;
  24186. this.updateFloat4 = this._updateFloat4ForUniform;
  24187. this.updateMatrix = this._updateMatrixForUniform;
  24188. this.updateVector3 = this._updateVector3ForUniform;
  24189. this.updateVector4 = this._updateVector4ForUniform;
  24190. this.updateColor3 = this._updateColor3ForUniform;
  24191. this.updateColor4 = this._updateColor4ForUniform;
  24192. }
  24193. }
  24194. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24195. // Properties
  24196. /**
  24197. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24198. * or just falling back on setUniformXXX calls.
  24199. */
  24200. get: function () {
  24201. return !this._noUBO;
  24202. },
  24203. enumerable: true,
  24204. configurable: true
  24205. });
  24206. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24207. /**
  24208. * Indicates if the WebGL underlying uniform buffer is in sync
  24209. * with the javascript cache data.
  24210. */
  24211. get: function () {
  24212. return !this._needSync;
  24213. },
  24214. enumerable: true,
  24215. configurable: true
  24216. });
  24217. /**
  24218. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24219. * Also, a dynamic UniformBuffer will disable cache verification and always
  24220. * update the underlying WebGL uniform buffer to the GPU.
  24221. */
  24222. UniformBuffer.prototype.isDynamic = function () {
  24223. return this._dynamic;
  24224. };
  24225. /**
  24226. * The data cache on JS side.
  24227. */
  24228. UniformBuffer.prototype.getData = function () {
  24229. return this._bufferData;
  24230. };
  24231. /**
  24232. * The underlying WebGL Uniform buffer.
  24233. */
  24234. UniformBuffer.prototype.getBuffer = function () {
  24235. return this._buffer;
  24236. };
  24237. /**
  24238. * std140 layout specifies how to align data within an UBO structure.
  24239. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24240. * for specs.
  24241. */
  24242. UniformBuffer.prototype._fillAlignment = function (size) {
  24243. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24244. // and 4x4 matrices
  24245. // TODO : change if other types are used
  24246. var alignment;
  24247. if (size <= 2) {
  24248. alignment = size;
  24249. }
  24250. else {
  24251. alignment = 4;
  24252. }
  24253. if ((this._uniformLocationPointer % alignment) !== 0) {
  24254. var oldPointer = this._uniformLocationPointer;
  24255. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24256. var diff = this._uniformLocationPointer - oldPointer;
  24257. for (var i = 0; i < diff; i++) {
  24258. this._data.push(0);
  24259. }
  24260. }
  24261. };
  24262. /**
  24263. * Adds an uniform in the buffer.
  24264. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24265. * for the layout to be correct !
  24266. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24267. * @param {number|number[]} size Data size, or data directly.
  24268. */
  24269. UniformBuffer.prototype.addUniform = function (name, size) {
  24270. if (this._noUBO) {
  24271. return;
  24272. }
  24273. if (this._uniformLocations[name] !== undefined) {
  24274. // Already existing uniform
  24275. return;
  24276. }
  24277. // This function must be called in the order of the shader layout !
  24278. // size can be the size of the uniform, or data directly
  24279. var data;
  24280. if (size instanceof Array) {
  24281. data = size;
  24282. size = data.length;
  24283. }
  24284. else {
  24285. size = size;
  24286. data = [];
  24287. // Fill with zeros
  24288. for (var i = 0; i < size; i++) {
  24289. data.push(0);
  24290. }
  24291. }
  24292. this._fillAlignment(size);
  24293. this._uniformSizes[name] = size;
  24294. this._uniformLocations[name] = this._uniformLocationPointer;
  24295. this._uniformLocationPointer += size;
  24296. for (var i = 0; i < size; i++) {
  24297. this._data.push(data[i]);
  24298. }
  24299. this._needSync = true;
  24300. };
  24301. /**
  24302. * Wrapper for addUniform.
  24303. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24304. * @param {Matrix} mat A 4x4 matrix.
  24305. */
  24306. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24307. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24308. };
  24309. /**
  24310. * Wrapper for addUniform.
  24311. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24312. * @param {number} x
  24313. * @param {number} y
  24314. */
  24315. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24316. var temp = [x, y];
  24317. this.addUniform(name, temp);
  24318. };
  24319. /**
  24320. * Wrapper for addUniform.
  24321. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24322. * @param {number} x
  24323. * @param {number} y
  24324. * @param {number} z
  24325. */
  24326. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24327. var temp = [x, y, z];
  24328. this.addUniform(name, temp);
  24329. };
  24330. /**
  24331. * Wrapper for addUniform.
  24332. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24333. * @param {Color3} color
  24334. */
  24335. UniformBuffer.prototype.addColor3 = function (name, color) {
  24336. var temp = [];
  24337. color.toArray(temp);
  24338. this.addUniform(name, temp);
  24339. };
  24340. /**
  24341. * Wrapper for addUniform.
  24342. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24343. * @param {Color3} color
  24344. * @param {number} alpha
  24345. */
  24346. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24347. var temp = [];
  24348. color.toArray(temp);
  24349. temp.push(alpha);
  24350. this.addUniform(name, temp);
  24351. };
  24352. /**
  24353. * Wrapper for addUniform.
  24354. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24355. * @param {Vector3} vector
  24356. */
  24357. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24358. var temp = [];
  24359. vector.toArray(temp);
  24360. this.addUniform(name, temp);
  24361. };
  24362. /**
  24363. * Wrapper for addUniform.
  24364. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24365. */
  24366. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24367. this.addUniform(name, 12);
  24368. };
  24369. /**
  24370. * Wrapper for addUniform.
  24371. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24372. */
  24373. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24374. this.addUniform(name, 8);
  24375. };
  24376. /**
  24377. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24378. */
  24379. UniformBuffer.prototype.create = function () {
  24380. if (this._noUBO) {
  24381. return;
  24382. }
  24383. if (this._buffer) {
  24384. return; // nothing to do
  24385. }
  24386. // See spec, alignment must be filled as a vec4
  24387. this._fillAlignment(4);
  24388. this._bufferData = new Float32Array(this._data);
  24389. if (this._dynamic) {
  24390. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24391. }
  24392. else {
  24393. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24394. }
  24395. this._needSync = true;
  24396. };
  24397. /**
  24398. * Updates the WebGL Uniform Buffer on the GPU.
  24399. * If the `dynamic` flag is set to true, no cache comparison is done.
  24400. * Otherwise, the buffer will be updated only if the cache differs.
  24401. */
  24402. UniformBuffer.prototype.update = function () {
  24403. if (!this._buffer) {
  24404. this.create();
  24405. return;
  24406. }
  24407. if (!this._dynamic && !this._needSync) {
  24408. return;
  24409. }
  24410. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24411. this._needSync = false;
  24412. };
  24413. /**
  24414. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24415. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24416. * @param {number[]|Float32Array} data Flattened data
  24417. * @param {number} size Size of the data.
  24418. */
  24419. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24420. var location = this._uniformLocations[uniformName];
  24421. if (location === undefined) {
  24422. if (this._buffer) {
  24423. // Cannot add an uniform if the buffer is already created
  24424. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24425. return;
  24426. }
  24427. this.addUniform(uniformName, size);
  24428. location = this._uniformLocations[uniformName];
  24429. }
  24430. if (!this._buffer) {
  24431. this.create();
  24432. }
  24433. if (!this._dynamic) {
  24434. // Cache for static uniform buffers
  24435. var changed = false;
  24436. for (var i = 0; i < size; i++) {
  24437. if (this._bufferData[location + i] !== data[i]) {
  24438. changed = true;
  24439. this._bufferData[location + i] = data[i];
  24440. }
  24441. }
  24442. this._needSync = this._needSync || changed;
  24443. }
  24444. else {
  24445. // No cache for dynamic
  24446. for (var i = 0; i < size; i++) {
  24447. this._bufferData[location + i] = data[i];
  24448. }
  24449. }
  24450. };
  24451. // Update methods
  24452. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24453. // To match std140, matrix must be realigned
  24454. for (var i = 0; i < 3; i++) {
  24455. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24456. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24457. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24458. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24459. }
  24460. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24461. };
  24462. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24463. this._currentEffect.setMatrix3x3(name, matrix);
  24464. };
  24465. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24466. this._currentEffect.setMatrix2x2(name, matrix);
  24467. };
  24468. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24469. // To match std140, matrix must be realigned
  24470. for (var i = 0; i < 2; i++) {
  24471. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24472. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24473. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24474. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24475. }
  24476. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24477. };
  24478. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24479. this._currentEffect.setFloat(name, x);
  24480. };
  24481. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24482. UniformBuffer._tempBuffer[0] = x;
  24483. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24484. };
  24485. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24486. this._currentEffect.setFloat2(name, x, y);
  24487. };
  24488. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24489. UniformBuffer._tempBuffer[0] = x;
  24490. UniformBuffer._tempBuffer[1] = y;
  24491. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24492. };
  24493. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24494. if (suffix === void 0) { suffix = ""; }
  24495. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24496. };
  24497. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24498. if (suffix === void 0) { suffix = ""; }
  24499. UniformBuffer._tempBuffer[0] = x;
  24500. UniformBuffer._tempBuffer[1] = y;
  24501. UniformBuffer._tempBuffer[2] = z;
  24502. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24503. };
  24504. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24505. if (suffix === void 0) { suffix = ""; }
  24506. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24507. };
  24508. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24509. if (suffix === void 0) { suffix = ""; }
  24510. UniformBuffer._tempBuffer[0] = x;
  24511. UniformBuffer._tempBuffer[1] = y;
  24512. UniformBuffer._tempBuffer[2] = z;
  24513. UniformBuffer._tempBuffer[3] = w;
  24514. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24515. };
  24516. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24517. this._currentEffect.setMatrix(name, mat);
  24518. };
  24519. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24520. this.updateUniform(name, mat.toArray(), 16);
  24521. };
  24522. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24523. this._currentEffect.setVector3(name, vector);
  24524. };
  24525. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24526. vector.toArray(UniformBuffer._tempBuffer);
  24527. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24528. };
  24529. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24530. this._currentEffect.setVector4(name, vector);
  24531. };
  24532. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24533. vector.toArray(UniformBuffer._tempBuffer);
  24534. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24535. };
  24536. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24537. if (suffix === void 0) { suffix = ""; }
  24538. this._currentEffect.setColor3(name + suffix, color);
  24539. };
  24540. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24541. if (suffix === void 0) { suffix = ""; }
  24542. color.toArray(UniformBuffer._tempBuffer);
  24543. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24544. };
  24545. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24546. if (suffix === void 0) { suffix = ""; }
  24547. this._currentEffect.setColor4(name + suffix, color, alpha);
  24548. };
  24549. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24550. if (suffix === void 0) { suffix = ""; }
  24551. color.toArray(UniformBuffer._tempBuffer);
  24552. UniformBuffer._tempBuffer[3] = alpha;
  24553. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24554. };
  24555. /**
  24556. * Sets a sampler uniform on the effect.
  24557. * @param {string} name Name of the sampler.
  24558. * @param {Texture} texture
  24559. */
  24560. UniformBuffer.prototype.setTexture = function (name, texture) {
  24561. this._currentEffect.setTexture(name, texture);
  24562. };
  24563. /**
  24564. * Directly updates the value of the uniform in the cache AND on the GPU.
  24565. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24566. * @param {number[]|Float32Array} data Flattened data
  24567. */
  24568. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24569. this.updateUniform(uniformName, data, data.length);
  24570. this.update();
  24571. };
  24572. /**
  24573. * Binds this uniform buffer to an effect.
  24574. * @param {Effect} effect
  24575. * @param {string} name Name of the uniform block in the shader.
  24576. */
  24577. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24578. this._currentEffect = effect;
  24579. if (this._noUBO) {
  24580. return;
  24581. }
  24582. effect.bindUniformBuffer(this._buffer, name);
  24583. };
  24584. /**
  24585. * Disposes the uniform buffer.
  24586. */
  24587. UniformBuffer.prototype.dispose = function () {
  24588. if (!this._buffer) {
  24589. return;
  24590. }
  24591. if (this._engine._releaseBuffer(this._buffer)) {
  24592. this._buffer = null;
  24593. }
  24594. };
  24595. return UniformBuffer;
  24596. }());
  24597. // Pool for avoiding memory leaks
  24598. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24599. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24600. BABYLON.UniformBuffer = UniformBuffer;
  24601. })(BABYLON || (BABYLON = {}));
  24602. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24603. var BABYLON;
  24604. (function (BABYLON) {
  24605. var PushMaterial = (function (_super) {
  24606. __extends(PushMaterial, _super);
  24607. function PushMaterial(name, scene) {
  24608. var _this = _super.call(this, name, scene) || this;
  24609. _this.storeEffectOnSubMeshes = true;
  24610. return _this;
  24611. }
  24612. PushMaterial.prototype.getEffect = function () {
  24613. return this._activeEffect;
  24614. };
  24615. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24616. if (!mesh) {
  24617. return false;
  24618. }
  24619. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24620. return true;
  24621. }
  24622. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24623. };
  24624. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24625. this._activeEffect.setMatrix("world", world);
  24626. };
  24627. PushMaterial.prototype.bind = function (world, mesh) {
  24628. if (!mesh) {
  24629. return;
  24630. }
  24631. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24632. };
  24633. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24634. _super.prototype._afterBind.call(this, mesh);
  24635. this.getScene()._cachedEffect = effect;
  24636. };
  24637. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24638. if (visibility === void 0) { visibility = 0; }
  24639. return scene.isCachedMaterialValid(this, effect, visibility);
  24640. };
  24641. PushMaterial.prototype.markAsDirty = function (flag) {
  24642. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24643. this._markAllSubMeshesAsTexturesDirty();
  24644. }
  24645. if (flag & BABYLON.Material.LightDirtyFlag) {
  24646. this._markAllSubMeshesAsLightsDirty();
  24647. }
  24648. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24649. this._markAllSubMeshesAsFresnelDirty();
  24650. }
  24651. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24652. this._markAllSubMeshesAsAttributesDirty();
  24653. }
  24654. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24655. this._markAllSubMeshesAsMiscDirty();
  24656. }
  24657. this.getScene().resetCachedMaterial();
  24658. };
  24659. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24660. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24661. var mesh = _a[_i];
  24662. if (!mesh.subMeshes) {
  24663. continue;
  24664. }
  24665. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24666. var subMesh = _c[_b];
  24667. if (subMesh.getMaterial() !== this) {
  24668. continue;
  24669. }
  24670. if (!subMesh._materialDefines) {
  24671. return;
  24672. }
  24673. func(subMesh._materialDefines);
  24674. }
  24675. }
  24676. };
  24677. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24678. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24679. };
  24680. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24681. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24682. };
  24683. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24684. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24685. };
  24686. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24687. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24688. };
  24689. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24690. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24691. };
  24692. return PushMaterial;
  24693. }(BABYLON.Material));
  24694. BABYLON.PushMaterial = PushMaterial;
  24695. })(BABYLON || (BABYLON = {}));
  24696. //# sourceMappingURL=babylon.pushMaterial.js.map
  24697. var BABYLON;
  24698. (function (BABYLON) {
  24699. var VertexData = (function () {
  24700. function VertexData() {
  24701. }
  24702. VertexData.prototype.set = function (data, kind) {
  24703. switch (kind) {
  24704. case BABYLON.VertexBuffer.PositionKind:
  24705. this.positions = data;
  24706. break;
  24707. case BABYLON.VertexBuffer.NormalKind:
  24708. this.normals = data;
  24709. break;
  24710. case BABYLON.VertexBuffer.TangentKind:
  24711. this.tangents = data;
  24712. break;
  24713. case BABYLON.VertexBuffer.UVKind:
  24714. this.uvs = data;
  24715. break;
  24716. case BABYLON.VertexBuffer.UV2Kind:
  24717. this.uvs2 = data;
  24718. break;
  24719. case BABYLON.VertexBuffer.UV3Kind:
  24720. this.uvs3 = data;
  24721. break;
  24722. case BABYLON.VertexBuffer.UV4Kind:
  24723. this.uvs4 = data;
  24724. break;
  24725. case BABYLON.VertexBuffer.UV5Kind:
  24726. this.uvs5 = data;
  24727. break;
  24728. case BABYLON.VertexBuffer.UV6Kind:
  24729. this.uvs6 = data;
  24730. break;
  24731. case BABYLON.VertexBuffer.ColorKind:
  24732. this.colors = data;
  24733. break;
  24734. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24735. this.matricesIndices = data;
  24736. break;
  24737. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24738. this.matricesWeights = data;
  24739. break;
  24740. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24741. this.matricesIndicesExtra = data;
  24742. break;
  24743. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24744. this.matricesWeightsExtra = data;
  24745. break;
  24746. }
  24747. };
  24748. /**
  24749. * Associates the vertexData to the passed Mesh.
  24750. * Sets it as updatable or not (default `false`).
  24751. * Returns the VertexData.
  24752. */
  24753. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24754. this._applyTo(mesh, updatable);
  24755. return this;
  24756. };
  24757. /**
  24758. * Associates the vertexData to the passed Geometry.
  24759. * Sets it as updatable or not (default `false`).
  24760. * Returns the VertexData.
  24761. */
  24762. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24763. this._applyTo(geometry, updatable);
  24764. return this;
  24765. };
  24766. /**
  24767. * Updates the associated mesh.
  24768. * Returns the VertexData.
  24769. */
  24770. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24771. this._update(mesh);
  24772. return this;
  24773. };
  24774. /**
  24775. * Updates the associated geometry.
  24776. * Returns the VertexData.
  24777. */
  24778. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24779. this._update(geometry);
  24780. return this;
  24781. };
  24782. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24783. if (this.positions) {
  24784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24785. }
  24786. if (this.normals) {
  24787. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24788. }
  24789. if (this.tangents) {
  24790. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24791. }
  24792. if (this.uvs) {
  24793. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24794. }
  24795. if (this.uvs2) {
  24796. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24797. }
  24798. if (this.uvs3) {
  24799. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24800. }
  24801. if (this.uvs4) {
  24802. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24803. }
  24804. if (this.uvs5) {
  24805. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24806. }
  24807. if (this.uvs6) {
  24808. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24809. }
  24810. if (this.colors) {
  24811. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24812. }
  24813. if (this.matricesIndices) {
  24814. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24815. }
  24816. if (this.matricesWeights) {
  24817. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24818. }
  24819. if (this.matricesIndicesExtra) {
  24820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24821. }
  24822. if (this.matricesWeightsExtra) {
  24823. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24824. }
  24825. if (this.indices) {
  24826. meshOrGeometry.setIndices(this.indices);
  24827. }
  24828. return this;
  24829. };
  24830. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24831. if (this.positions) {
  24832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24833. }
  24834. if (this.normals) {
  24835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24836. }
  24837. if (this.tangents) {
  24838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24839. }
  24840. if (this.uvs) {
  24841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24842. }
  24843. if (this.uvs2) {
  24844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24845. }
  24846. if (this.uvs3) {
  24847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24848. }
  24849. if (this.uvs4) {
  24850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24851. }
  24852. if (this.uvs5) {
  24853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24854. }
  24855. if (this.uvs6) {
  24856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24857. }
  24858. if (this.colors) {
  24859. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24860. }
  24861. if (this.matricesIndices) {
  24862. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24863. }
  24864. if (this.matricesWeights) {
  24865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24866. }
  24867. if (this.matricesIndicesExtra) {
  24868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24869. }
  24870. if (this.matricesWeightsExtra) {
  24871. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24872. }
  24873. if (this.indices) {
  24874. meshOrGeometry.setIndices(this.indices);
  24875. }
  24876. return this;
  24877. };
  24878. /**
  24879. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24880. * Returns the VertexData.
  24881. */
  24882. VertexData.prototype.transform = function (matrix) {
  24883. var transformed = BABYLON.Vector3.Zero();
  24884. var index;
  24885. if (this.positions) {
  24886. var position = BABYLON.Vector3.Zero();
  24887. for (index = 0; index < this.positions.length; index += 3) {
  24888. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24889. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24890. this.positions[index] = transformed.x;
  24891. this.positions[index + 1] = transformed.y;
  24892. this.positions[index + 2] = transformed.z;
  24893. }
  24894. }
  24895. if (this.normals) {
  24896. var normal = BABYLON.Vector3.Zero();
  24897. for (index = 0; index < this.normals.length; index += 3) {
  24898. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24899. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24900. this.normals[index] = transformed.x;
  24901. this.normals[index + 1] = transformed.y;
  24902. this.normals[index + 2] = transformed.z;
  24903. }
  24904. }
  24905. if (this.tangents) {
  24906. var tangent = BABYLON.Vector4.Zero();
  24907. var tangentTransformed = BABYLON.Vector4.Zero();
  24908. for (index = 0; index < this.tangents.length; index += 4) {
  24909. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24910. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24911. this.tangents[index] = tangentTransformed.x;
  24912. this.tangents[index + 1] = tangentTransformed.y;
  24913. this.tangents[index + 2] = tangentTransformed.z;
  24914. this.tangents[index + 3] = tangentTransformed.w;
  24915. }
  24916. }
  24917. return this;
  24918. };
  24919. /**
  24920. * Merges the passed VertexData into the current one.
  24921. * Returns the modified VertexData.
  24922. */
  24923. VertexData.prototype.merge = function (other) {
  24924. if (other.indices) {
  24925. if (!this.indices) {
  24926. this.indices = [];
  24927. }
  24928. var offset = this.positions ? this.positions.length / 3 : 0;
  24929. for (var index = 0; index < other.indices.length; index++) {
  24930. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24931. this.indices.push(other.indices[index] + offset);
  24932. }
  24933. }
  24934. this.positions = this._mergeElement(this.positions, other.positions);
  24935. this.normals = this._mergeElement(this.normals, other.normals);
  24936. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24937. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24938. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24939. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24940. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24941. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24942. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24943. this.colors = this._mergeElement(this.colors, other.colors);
  24944. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24945. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24946. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24947. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24948. return this;
  24949. };
  24950. VertexData.prototype._mergeElement = function (source, other) {
  24951. if (!other)
  24952. return source;
  24953. if (!source)
  24954. return other;
  24955. var len = other.length + source.length;
  24956. var isSrcTypedArray = source instanceof Float32Array;
  24957. var isOthTypedArray = other instanceof Float32Array;
  24958. // use non-loop method when the source is Float32Array
  24959. if (isSrcTypedArray) {
  24960. var ret32 = new Float32Array(len);
  24961. ret32.set(source);
  24962. ret32.set(other, source.length);
  24963. return ret32;
  24964. // source is number[], when other is also use concat
  24965. }
  24966. else if (!isOthTypedArray) {
  24967. return source.concat(other);
  24968. // source is a number[], but other is a Float32Array, loop required
  24969. }
  24970. else {
  24971. var ret = source.slice(0); // copy source to a separate array
  24972. for (var i = 0, len = other.length; i < len; i++) {
  24973. ret.push(other[i]);
  24974. }
  24975. return ret;
  24976. }
  24977. };
  24978. /**
  24979. * Serializes the VertexData.
  24980. * Returns a serialized object.
  24981. */
  24982. VertexData.prototype.serialize = function () {
  24983. var serializationObject = this.serialize();
  24984. if (this.positions) {
  24985. serializationObject.positions = this.positions;
  24986. }
  24987. if (this.normals) {
  24988. serializationObject.normals = this.normals;
  24989. }
  24990. if (this.tangents) {
  24991. serializationObject.tangents = this.tangents;
  24992. }
  24993. if (this.uvs) {
  24994. serializationObject.uvs = this.uvs;
  24995. }
  24996. if (this.uvs2) {
  24997. serializationObject.uvs2 = this.uvs2;
  24998. }
  24999. if (this.uvs3) {
  25000. serializationObject.uvs3 = this.uvs3;
  25001. }
  25002. if (this.uvs4) {
  25003. serializationObject.uvs4 = this.uvs4;
  25004. }
  25005. if (this.uvs5) {
  25006. serializationObject.uvs5 = this.uvs5;
  25007. }
  25008. if (this.uvs6) {
  25009. serializationObject.uvs6 = this.uvs6;
  25010. }
  25011. if (this.colors) {
  25012. serializationObject.colors = this.colors;
  25013. }
  25014. if (this.matricesIndices) {
  25015. serializationObject.matricesIndices = this.matricesIndices;
  25016. serializationObject.matricesIndices._isExpanded = true;
  25017. }
  25018. if (this.matricesWeights) {
  25019. serializationObject.matricesWeights = this.matricesWeights;
  25020. }
  25021. if (this.matricesIndicesExtra) {
  25022. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25023. serializationObject.matricesIndicesExtra._isExpanded = true;
  25024. }
  25025. if (this.matricesWeightsExtra) {
  25026. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25027. }
  25028. serializationObject.indices = this.indices;
  25029. return serializationObject;
  25030. };
  25031. // Statics
  25032. /**
  25033. * Returns the object VertexData associated to the passed mesh.
  25034. */
  25035. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25036. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25037. };
  25038. /**
  25039. * Returns the object VertexData associated to the passed geometry.
  25040. */
  25041. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25042. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25043. };
  25044. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25045. var result = new VertexData();
  25046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25047. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25048. }
  25049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25050. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25051. }
  25052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25053. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25054. }
  25055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25056. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25057. }
  25058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25059. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25060. }
  25061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25062. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25063. }
  25064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25065. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25066. }
  25067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25068. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25069. }
  25070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25071. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25072. }
  25073. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25074. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25075. }
  25076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25077. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25078. }
  25079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25080. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25081. }
  25082. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25083. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25084. }
  25085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25086. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25087. }
  25088. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25089. return result;
  25090. };
  25091. /**
  25092. * Creates the vertexData of the Ribbon.
  25093. */
  25094. VertexData.CreateRibbon = function (options) {
  25095. var pathArray = options.pathArray;
  25096. var closeArray = options.closeArray || false;
  25097. var closePath = options.closePath || false;
  25098. var invertUV = options.invertUV || false;
  25099. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25100. var offset = options.offset || defaultOffset;
  25101. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25102. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25103. var customUV = options.uvs;
  25104. var customColors = options.colors;
  25105. var positions = [];
  25106. var indices = [];
  25107. var normals = [];
  25108. var uvs = [];
  25109. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25110. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25111. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25112. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25113. var minlg; // minimal length among all paths from pathArray
  25114. var lg = []; // array of path lengths : nb of vertex per path
  25115. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25116. var p; // path iterator
  25117. var i; // point iterator
  25118. var j; // point iterator
  25119. // if single path in pathArray
  25120. if (pathArray.length < 2) {
  25121. var ar1 = [];
  25122. var ar2 = [];
  25123. for (i = 0; i < pathArray[0].length - offset; i++) {
  25124. ar1.push(pathArray[0][i]);
  25125. ar2.push(pathArray[0][i + offset]);
  25126. }
  25127. pathArray = [ar1, ar2];
  25128. }
  25129. // positions and horizontal distances (u)
  25130. var idc = 0;
  25131. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25132. var path;
  25133. var l;
  25134. minlg = pathArray[0].length;
  25135. var vectlg;
  25136. var dist;
  25137. for (p = 0; p < pathArray.length; p++) {
  25138. uTotalDistance[p] = 0;
  25139. us[p] = [0];
  25140. path = pathArray[p];
  25141. l = path.length;
  25142. minlg = (minlg < l) ? minlg : l;
  25143. j = 0;
  25144. while (j < l) {
  25145. positions.push(path[j].x, path[j].y, path[j].z);
  25146. if (j > 0) {
  25147. vectlg = path[j].subtract(path[j - 1]).length();
  25148. dist = vectlg + uTotalDistance[p];
  25149. us[p].push(dist);
  25150. uTotalDistance[p] = dist;
  25151. }
  25152. j++;
  25153. }
  25154. if (closePath) {
  25155. j--;
  25156. positions.push(path[0].x, path[0].y, path[0].z);
  25157. vectlg = path[j].subtract(path[0]).length();
  25158. dist = vectlg + uTotalDistance[p];
  25159. us[p].push(dist);
  25160. uTotalDistance[p] = dist;
  25161. }
  25162. lg[p] = l + closePathCorr;
  25163. idx[p] = idc;
  25164. idc += (l + closePathCorr);
  25165. }
  25166. // vertical distances (v)
  25167. var path1;
  25168. var path2;
  25169. var vertex1;
  25170. var vertex2;
  25171. for (i = 0; i < minlg + closePathCorr; i++) {
  25172. vTotalDistance[i] = 0;
  25173. vs[i] = [0];
  25174. for (p = 0; p < pathArray.length - 1; p++) {
  25175. path1 = pathArray[p];
  25176. path2 = pathArray[p + 1];
  25177. if (i === minlg) {
  25178. vertex1 = path1[0];
  25179. vertex2 = path2[0];
  25180. }
  25181. else {
  25182. vertex1 = path1[i];
  25183. vertex2 = path2[i];
  25184. }
  25185. vectlg = vertex2.subtract(vertex1).length();
  25186. dist = vectlg + vTotalDistance[i];
  25187. vs[i].push(dist);
  25188. vTotalDistance[i] = dist;
  25189. }
  25190. if (closeArray) {
  25191. path1 = pathArray[p];
  25192. path2 = pathArray[0];
  25193. if (i === minlg) {
  25194. vertex2 = path2[0];
  25195. }
  25196. vectlg = vertex2.subtract(vertex1).length();
  25197. dist = vectlg + vTotalDistance[i];
  25198. vTotalDistance[i] = dist;
  25199. }
  25200. }
  25201. // uvs
  25202. var u;
  25203. var v;
  25204. if (customUV) {
  25205. for (p = 0; p < customUV.length; p++) {
  25206. uvs.push(customUV[p].x, customUV[p].y);
  25207. }
  25208. }
  25209. else {
  25210. for (p = 0; p < pathArray.length; p++) {
  25211. for (i = 0; i < minlg + closePathCorr; i++) {
  25212. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25213. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25214. if (invertUV) {
  25215. uvs.push(v, u);
  25216. }
  25217. else {
  25218. uvs.push(u, v);
  25219. }
  25220. }
  25221. }
  25222. }
  25223. // indices
  25224. p = 0; // path index
  25225. var pi = 0; // positions array index
  25226. var l1 = lg[p] - 1; // path1 length
  25227. var l2 = lg[p + 1] - 1; // path2 length
  25228. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25229. var shft = idx[1] - idx[0]; // shift
  25230. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25231. while (pi <= min && p < path1nb) {
  25232. // 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
  25233. indices.push(pi, pi + shft, pi + 1);
  25234. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25235. pi += 1;
  25236. if (pi === min) {
  25237. p++;
  25238. if (p === lg.length - 1) {
  25239. shft = idx[0] - idx[p];
  25240. l1 = lg[p] - 1;
  25241. l2 = lg[0] - 1;
  25242. }
  25243. else {
  25244. shft = idx[p + 1] - idx[p];
  25245. l1 = lg[p] - 1;
  25246. l2 = lg[p + 1] - 1;
  25247. }
  25248. pi = idx[p];
  25249. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25250. }
  25251. }
  25252. // normals
  25253. VertexData.ComputeNormals(positions, indices, normals);
  25254. if (closePath) {
  25255. var indexFirst = 0;
  25256. var indexLast = 0;
  25257. for (p = 0; p < pathArray.length; p++) {
  25258. indexFirst = idx[p] * 3;
  25259. if (p + 1 < pathArray.length) {
  25260. indexLast = (idx[p + 1] - 1) * 3;
  25261. }
  25262. else {
  25263. indexLast = normals.length - 3;
  25264. }
  25265. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25266. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25267. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25268. normals[indexLast] = normals[indexFirst];
  25269. normals[indexLast + 1] = normals[indexFirst + 1];
  25270. normals[indexLast + 2] = normals[indexFirst + 2];
  25271. }
  25272. }
  25273. // sides
  25274. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25275. // Colors
  25276. if (customColors) {
  25277. var colors = new Float32Array(customColors.length * 4);
  25278. for (var c = 0; c < customColors.length; c++) {
  25279. colors[c * 4] = customColors[c].r;
  25280. colors[c * 4 + 1] = customColors[c].g;
  25281. colors[c * 4 + 2] = customColors[c].b;
  25282. colors[c * 4 + 3] = customColors[c].a;
  25283. }
  25284. }
  25285. // Result
  25286. var vertexData = new VertexData();
  25287. var positions32 = new Float32Array(positions);
  25288. var normals32 = new Float32Array(normals);
  25289. var uvs32 = new Float32Array(uvs);
  25290. vertexData.indices = indices;
  25291. vertexData.positions = positions32;
  25292. vertexData.normals = normals32;
  25293. vertexData.uvs = uvs32;
  25294. if (customColors) {
  25295. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25296. }
  25297. if (closePath) {
  25298. vertexData._idx = idx;
  25299. }
  25300. return vertexData;
  25301. };
  25302. /**
  25303. * Creates the VertexData of the Box.
  25304. */
  25305. VertexData.CreateBox = function (options) {
  25306. var normalsSource = [
  25307. new BABYLON.Vector3(0, 0, 1),
  25308. new BABYLON.Vector3(0, 0, -1),
  25309. new BABYLON.Vector3(1, 0, 0),
  25310. new BABYLON.Vector3(-1, 0, 0),
  25311. new BABYLON.Vector3(0, 1, 0),
  25312. new BABYLON.Vector3(0, -1, 0)
  25313. ];
  25314. var indices = [];
  25315. var positions = [];
  25316. var normals = [];
  25317. var uvs = [];
  25318. var width = options.width || options.size || 1;
  25319. var height = options.height || options.size || 1;
  25320. var depth = options.depth || options.size || 1;
  25321. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25322. var faceUV = options.faceUV || new Array(6);
  25323. var faceColors = options.faceColors;
  25324. var colors = [];
  25325. // default face colors and UV if undefined
  25326. for (var f = 0; f < 6; f++) {
  25327. if (faceUV[f] === undefined) {
  25328. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25329. }
  25330. if (faceColors && faceColors[f] === undefined) {
  25331. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25332. }
  25333. }
  25334. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25335. // Create each face in turn.
  25336. for (var index = 0; index < normalsSource.length; index++) {
  25337. var normal = normalsSource[index];
  25338. // Get two vectors perpendicular to the face normal and to each other.
  25339. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25340. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25341. // Six indices (two triangles) per face.
  25342. var verticesLength = positions.length / 3;
  25343. indices.push(verticesLength);
  25344. indices.push(verticesLength + 1);
  25345. indices.push(verticesLength + 2);
  25346. indices.push(verticesLength);
  25347. indices.push(verticesLength + 2);
  25348. indices.push(verticesLength + 3);
  25349. // Four vertices per face.
  25350. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25351. positions.push(vertex.x, vertex.y, vertex.z);
  25352. normals.push(normal.x, normal.y, normal.z);
  25353. uvs.push(faceUV[index].z, faceUV[index].w);
  25354. if (faceColors) {
  25355. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25356. }
  25357. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25358. positions.push(vertex.x, vertex.y, vertex.z);
  25359. normals.push(normal.x, normal.y, normal.z);
  25360. uvs.push(faceUV[index].x, faceUV[index].w);
  25361. if (faceColors) {
  25362. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25363. }
  25364. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25365. positions.push(vertex.x, vertex.y, vertex.z);
  25366. normals.push(normal.x, normal.y, normal.z);
  25367. uvs.push(faceUV[index].x, faceUV[index].y);
  25368. if (faceColors) {
  25369. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25370. }
  25371. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25372. positions.push(vertex.x, vertex.y, vertex.z);
  25373. normals.push(normal.x, normal.y, normal.z);
  25374. uvs.push(faceUV[index].z, faceUV[index].y);
  25375. if (faceColors) {
  25376. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25377. }
  25378. }
  25379. // sides
  25380. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25381. // Result
  25382. var vertexData = new VertexData();
  25383. vertexData.indices = indices;
  25384. vertexData.positions = positions;
  25385. vertexData.normals = normals;
  25386. vertexData.uvs = uvs;
  25387. if (faceColors) {
  25388. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25389. vertexData.colors = totalColors;
  25390. }
  25391. return vertexData;
  25392. };
  25393. /**
  25394. * Creates the VertexData of the Sphere.
  25395. */
  25396. VertexData.CreateSphere = function (options) {
  25397. var segments = options.segments || 32;
  25398. var diameterX = options.diameterX || options.diameter || 1;
  25399. var diameterY = options.diameterY || options.diameter || 1;
  25400. var diameterZ = options.diameterZ || options.diameter || 1;
  25401. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25402. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25403. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25404. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25405. var totalZRotationSteps = 2 + segments;
  25406. var totalYRotationSteps = 2 * totalZRotationSteps;
  25407. var indices = [];
  25408. var positions = [];
  25409. var normals = [];
  25410. var uvs = [];
  25411. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25412. var normalizedZ = zRotationStep / totalZRotationSteps;
  25413. var angleZ = normalizedZ * Math.PI * slice;
  25414. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25415. var normalizedY = yRotationStep / totalYRotationSteps;
  25416. var angleY = normalizedY * Math.PI * 2 * arc;
  25417. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25418. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25419. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25420. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25421. var vertex = complete.multiply(radius);
  25422. var normal = complete.divide(radius).normalize();
  25423. positions.push(vertex.x, vertex.y, vertex.z);
  25424. normals.push(normal.x, normal.y, normal.z);
  25425. uvs.push(normalizedY, normalizedZ);
  25426. }
  25427. if (zRotationStep > 0) {
  25428. var verticesCount = positions.length / 3;
  25429. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25430. indices.push((firstIndex));
  25431. indices.push((firstIndex + 1));
  25432. indices.push(firstIndex + totalYRotationSteps + 1);
  25433. indices.push((firstIndex + totalYRotationSteps + 1));
  25434. indices.push((firstIndex + 1));
  25435. indices.push((firstIndex + totalYRotationSteps + 2));
  25436. }
  25437. }
  25438. }
  25439. // Sides
  25440. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25441. // Result
  25442. var vertexData = new VertexData();
  25443. vertexData.indices = indices;
  25444. vertexData.positions = positions;
  25445. vertexData.normals = normals;
  25446. vertexData.uvs = uvs;
  25447. return vertexData;
  25448. };
  25449. /**
  25450. * Creates the VertexData of the Cylinder or Cone.
  25451. */
  25452. VertexData.CreateCylinder = function (options) {
  25453. var height = options.height || 2;
  25454. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25455. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25456. var tessellation = options.tessellation || 24;
  25457. var subdivisions = options.subdivisions || 1;
  25458. var hasRings = options.hasRings;
  25459. var enclose = options.enclose;
  25460. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25461. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25462. var faceUV = options.faceUV || new Array(3);
  25463. var faceColors = options.faceColors;
  25464. // default face colors and UV if undefined
  25465. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25466. var ringNb = (hasRings) ? subdivisions : 1;
  25467. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25468. var f;
  25469. for (f = 0; f < surfaceNb; f++) {
  25470. if (faceColors && faceColors[f] === undefined) {
  25471. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25472. }
  25473. }
  25474. for (f = 0; f < surfaceNb; f++) {
  25475. if (faceUV && faceUV[f] === undefined) {
  25476. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25477. }
  25478. }
  25479. var indices = [];
  25480. var positions = [];
  25481. var normals = [];
  25482. var uvs = [];
  25483. var colors = [];
  25484. var angle_step = Math.PI * 2 * arc / tessellation;
  25485. var angle;
  25486. var h;
  25487. var radius;
  25488. var tan = (diameterBottom - diameterTop) / 2 / height;
  25489. var ringVertex = BABYLON.Vector3.Zero();
  25490. var ringNormal = BABYLON.Vector3.Zero();
  25491. var ringFirstVertex = BABYLON.Vector3.Zero();
  25492. var ringFirstNormal = BABYLON.Vector3.Zero();
  25493. var quadNormal = BABYLON.Vector3.Zero();
  25494. var Y = BABYLON.Axis.Y;
  25495. // positions, normals, uvs
  25496. var i;
  25497. var j;
  25498. var r;
  25499. var ringIdx = 1;
  25500. var s = 1; // surface index
  25501. var cs = 0;
  25502. var v = 0;
  25503. for (i = 0; i <= subdivisions; i++) {
  25504. h = i / subdivisions;
  25505. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25506. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25507. for (r = 0; r < ringIdx; r++) {
  25508. if (hasRings) {
  25509. s += r;
  25510. }
  25511. if (enclose) {
  25512. s += 2 * r;
  25513. }
  25514. for (j = 0; j <= tessellation; j++) {
  25515. angle = j * angle_step;
  25516. // position
  25517. ringVertex.x = Math.cos(-angle) * radius;
  25518. ringVertex.y = -height / 2 + h * height;
  25519. ringVertex.z = Math.sin(-angle) * radius;
  25520. // normal
  25521. if (diameterTop === 0 && i === subdivisions) {
  25522. // if no top cap, reuse former normals
  25523. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25524. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25525. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25526. }
  25527. else {
  25528. ringNormal.x = ringVertex.x;
  25529. ringNormal.z = ringVertex.z;
  25530. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25531. ringNormal.normalize();
  25532. }
  25533. // keep first ring vertex values for enclose
  25534. if (j === 0) {
  25535. ringFirstVertex.copyFrom(ringVertex);
  25536. ringFirstNormal.copyFrom(ringNormal);
  25537. }
  25538. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25539. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25540. if (hasRings) {
  25541. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25542. }
  25543. else {
  25544. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25545. }
  25546. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25547. if (faceColors) {
  25548. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25549. }
  25550. }
  25551. // if enclose, add four vertices and their dedicated normals
  25552. if (arc !== 1 && enclose) {
  25553. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25554. positions.push(0, ringVertex.y, 0);
  25555. positions.push(0, ringVertex.y, 0);
  25556. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25557. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25558. quadNormal.normalize();
  25559. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25560. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25561. quadNormal.normalize();
  25562. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25563. if (hasRings) {
  25564. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25565. }
  25566. else {
  25567. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25568. }
  25569. uvs.push(faceUV[s + 1].x, v);
  25570. uvs.push(faceUV[s + 1].z, v);
  25571. if (hasRings) {
  25572. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25573. }
  25574. else {
  25575. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25576. }
  25577. uvs.push(faceUV[s + 2].x, v);
  25578. uvs.push(faceUV[s + 2].z, v);
  25579. if (faceColors) {
  25580. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25581. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25582. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25583. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25584. }
  25585. }
  25586. if (cs !== s) {
  25587. cs = s;
  25588. }
  25589. }
  25590. }
  25591. // indices
  25592. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25593. var s;
  25594. i = 0;
  25595. for (s = 0; s < subdivisions; s++) {
  25596. for (j = 0; j < tessellation; j++) {
  25597. var i0 = i * (e + 1) + j;
  25598. var i1 = (i + 1) * (e + 1) + j;
  25599. var i2 = i * (e + 1) + (j + 1);
  25600. var i3 = (i + 1) * (e + 1) + (j + 1);
  25601. indices.push(i0, i1, i2);
  25602. indices.push(i3, i2, i1);
  25603. }
  25604. if (arc !== 1 && enclose) {
  25605. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25606. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25607. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25608. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25609. }
  25610. i = (hasRings) ? (i + 2) : (i + 1);
  25611. }
  25612. // Caps
  25613. var createCylinderCap = function (isTop) {
  25614. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25615. if (radius === 0) {
  25616. return;
  25617. }
  25618. // Cap positions, normals & uvs
  25619. var angle;
  25620. var circleVector;
  25621. var i;
  25622. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25623. var c;
  25624. if (faceColors) {
  25625. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25626. }
  25627. // cap center
  25628. var vbase = positions.length / 3;
  25629. var offset = isTop ? height / 2 : -height / 2;
  25630. var center = new BABYLON.Vector3(0, offset, 0);
  25631. positions.push(center.x, center.y, center.z);
  25632. normals.push(0, isTop ? 1 : -1, 0);
  25633. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25634. if (faceColors) {
  25635. colors.push(c.r, c.g, c.b, c.a);
  25636. }
  25637. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25638. for (i = 0; i <= tessellation; i++) {
  25639. angle = Math.PI * 2 * i * arc / tessellation;
  25640. var cos = Math.cos(-angle);
  25641. var sin = Math.sin(-angle);
  25642. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25643. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25644. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25645. normals.push(0, isTop ? 1 : -1, 0);
  25646. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25647. if (faceColors) {
  25648. colors.push(c.r, c.g, c.b, c.a);
  25649. }
  25650. }
  25651. // Cap indices
  25652. for (i = 0; i < tessellation; i++) {
  25653. if (!isTop) {
  25654. indices.push(vbase);
  25655. indices.push(vbase + (i + 1));
  25656. indices.push(vbase + (i + 2));
  25657. }
  25658. else {
  25659. indices.push(vbase);
  25660. indices.push(vbase + (i + 2));
  25661. indices.push(vbase + (i + 1));
  25662. }
  25663. }
  25664. };
  25665. // add caps to geometry
  25666. createCylinderCap(false);
  25667. createCylinderCap(true);
  25668. // Sides
  25669. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25670. var vertexData = new VertexData();
  25671. vertexData.indices = indices;
  25672. vertexData.positions = positions;
  25673. vertexData.normals = normals;
  25674. vertexData.uvs = uvs;
  25675. if (faceColors) {
  25676. vertexData.colors = colors;
  25677. }
  25678. return vertexData;
  25679. };
  25680. /**
  25681. * Creates the VertexData of the Torus.
  25682. */
  25683. VertexData.CreateTorus = function (options) {
  25684. var indices = [];
  25685. var positions = [];
  25686. var normals = [];
  25687. var uvs = [];
  25688. var diameter = options.diameter || 1;
  25689. var thickness = options.thickness || 0.5;
  25690. var tessellation = options.tessellation || 16;
  25691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25692. var stride = tessellation + 1;
  25693. for (var i = 0; i <= tessellation; i++) {
  25694. var u = i / tessellation;
  25695. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25696. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25697. for (var j = 0; j <= tessellation; j++) {
  25698. var v = 1 - j / tessellation;
  25699. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25700. var dx = Math.cos(innerAngle);
  25701. var dy = Math.sin(innerAngle);
  25702. // Create a vertex.
  25703. var normal = new BABYLON.Vector3(dx, dy, 0);
  25704. var position = normal.scale(thickness / 2);
  25705. var textureCoordinate = new BABYLON.Vector2(u, v);
  25706. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25707. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25708. positions.push(position.x, position.y, position.z);
  25709. normals.push(normal.x, normal.y, normal.z);
  25710. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25711. // And create indices for two triangles.
  25712. var nextI = (i + 1) % stride;
  25713. var nextJ = (j + 1) % stride;
  25714. indices.push(i * stride + j);
  25715. indices.push(i * stride + nextJ);
  25716. indices.push(nextI * stride + j);
  25717. indices.push(i * stride + nextJ);
  25718. indices.push(nextI * stride + nextJ);
  25719. indices.push(nextI * stride + j);
  25720. }
  25721. }
  25722. // Sides
  25723. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25724. // Result
  25725. var vertexData = new VertexData();
  25726. vertexData.indices = indices;
  25727. vertexData.positions = positions;
  25728. vertexData.normals = normals;
  25729. vertexData.uvs = uvs;
  25730. return vertexData;
  25731. };
  25732. /**
  25733. * Creates the VertexData of the LineSystem.
  25734. */
  25735. VertexData.CreateLineSystem = function (options) {
  25736. var indices = [];
  25737. var positions = [];
  25738. var lines = options.lines;
  25739. var idx = 0;
  25740. for (var l = 0; l < lines.length; l++) {
  25741. var points = lines[l];
  25742. for (var index = 0; index < points.length; index++) {
  25743. positions.push(points[index].x, points[index].y, points[index].z);
  25744. if (index > 0) {
  25745. indices.push(idx - 1);
  25746. indices.push(idx);
  25747. }
  25748. idx++;
  25749. }
  25750. }
  25751. var vertexData = new VertexData();
  25752. vertexData.indices = indices;
  25753. vertexData.positions = positions;
  25754. return vertexData;
  25755. };
  25756. /**
  25757. * Create the VertexData of the DashedLines.
  25758. */
  25759. VertexData.CreateDashedLines = function (options) {
  25760. var dashSize = options.dashSize || 3;
  25761. var gapSize = options.gapSize || 1;
  25762. var dashNb = options.dashNb || 200;
  25763. var points = options.points;
  25764. var positions = new Array();
  25765. var indices = new Array();
  25766. var curvect = BABYLON.Vector3.Zero();
  25767. var lg = 0;
  25768. var nb = 0;
  25769. var shft = 0;
  25770. var dashshft = 0;
  25771. var curshft = 0;
  25772. var idx = 0;
  25773. var i = 0;
  25774. for (i = 0; i < points.length - 1; i++) {
  25775. points[i + 1].subtractToRef(points[i], curvect);
  25776. lg += curvect.length();
  25777. }
  25778. shft = lg / dashNb;
  25779. dashshft = dashSize * shft / (dashSize + gapSize);
  25780. for (i = 0; i < points.length - 1; i++) {
  25781. points[i + 1].subtractToRef(points[i], curvect);
  25782. nb = Math.floor(curvect.length() / shft);
  25783. curvect.normalize();
  25784. for (var j = 0; j < nb; j++) {
  25785. curshft = shft * j;
  25786. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25787. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25788. indices.push(idx, idx + 1);
  25789. idx += 2;
  25790. }
  25791. }
  25792. // Result
  25793. var vertexData = new VertexData();
  25794. vertexData.positions = positions;
  25795. vertexData.indices = indices;
  25796. return vertexData;
  25797. };
  25798. /**
  25799. * Creates the VertexData of the Ground.
  25800. */
  25801. VertexData.CreateGround = function (options) {
  25802. var indices = [];
  25803. var positions = [];
  25804. var normals = [];
  25805. var uvs = [];
  25806. var row, col;
  25807. var width = options.width || 1;
  25808. var height = options.height || 1;
  25809. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25810. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25811. for (row = 0; row <= subdivisionsY; row++) {
  25812. for (col = 0; col <= subdivisionsX; col++) {
  25813. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25814. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25815. positions.push(position.x, position.y, position.z);
  25816. normals.push(normal.x, normal.y, normal.z);
  25817. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25818. }
  25819. }
  25820. for (row = 0; row < subdivisionsY; row++) {
  25821. for (col = 0; col < subdivisionsX; col++) {
  25822. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25823. indices.push(col + 1 + row * (subdivisionsX + 1));
  25824. indices.push(col + row * (subdivisionsX + 1));
  25825. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25826. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25827. indices.push(col + row * (subdivisionsX + 1));
  25828. }
  25829. }
  25830. // Result
  25831. var vertexData = new VertexData();
  25832. vertexData.indices = indices;
  25833. vertexData.positions = positions;
  25834. vertexData.normals = normals;
  25835. vertexData.uvs = uvs;
  25836. return vertexData;
  25837. };
  25838. /**
  25839. * Creates the VertexData of the TiledGround.
  25840. */
  25841. VertexData.CreateTiledGround = function (options) {
  25842. var xmin = options.xmin || -1.0;
  25843. var zmin = options.zmin || -1.0;
  25844. var xmax = options.xmax || 1.0;
  25845. var zmax = options.zmax || 1.0;
  25846. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25847. var precision = options.precision || { w: 1, h: 1 };
  25848. var indices = [];
  25849. var positions = [];
  25850. var normals = [];
  25851. var uvs = [];
  25852. var row, col, tileRow, tileCol;
  25853. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25854. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25855. precision.w = (precision.w < 1) ? 1 : precision.w;
  25856. precision.h = (precision.h < 1) ? 1 : precision.h;
  25857. var tileSize = {
  25858. 'w': (xmax - xmin) / subdivisions.w,
  25859. 'h': (zmax - zmin) / subdivisions.h
  25860. };
  25861. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25862. // Indices
  25863. var base = positions.length / 3;
  25864. var rowLength = precision.w + 1;
  25865. for (row = 0; row < precision.h; row++) {
  25866. for (col = 0; col < precision.w; col++) {
  25867. var square = [
  25868. base + col + row * rowLength,
  25869. base + (col + 1) + row * rowLength,
  25870. base + (col + 1) + (row + 1) * rowLength,
  25871. base + col + (row + 1) * rowLength
  25872. ];
  25873. indices.push(square[1]);
  25874. indices.push(square[2]);
  25875. indices.push(square[3]);
  25876. indices.push(square[0]);
  25877. indices.push(square[1]);
  25878. indices.push(square[3]);
  25879. }
  25880. }
  25881. // Position, normals and uvs
  25882. var position = BABYLON.Vector3.Zero();
  25883. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25884. for (row = 0; row <= precision.h; row++) {
  25885. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25886. for (col = 0; col <= precision.w; col++) {
  25887. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25888. position.y = 0;
  25889. positions.push(position.x, position.y, position.z);
  25890. normals.push(normal.x, normal.y, normal.z);
  25891. uvs.push(col / precision.w, row / precision.h);
  25892. }
  25893. }
  25894. }
  25895. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25896. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25897. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25898. }
  25899. }
  25900. // Result
  25901. var vertexData = new VertexData();
  25902. vertexData.indices = indices;
  25903. vertexData.positions = positions;
  25904. vertexData.normals = normals;
  25905. vertexData.uvs = uvs;
  25906. return vertexData;
  25907. };
  25908. /**
  25909. * Creates the VertexData of the Ground designed from a heightmap.
  25910. */
  25911. VertexData.CreateGroundFromHeightMap = function (options) {
  25912. var indices = [];
  25913. var positions = [];
  25914. var normals = [];
  25915. var uvs = [];
  25916. var row, col;
  25917. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25918. // Vertices
  25919. for (row = 0; row <= options.subdivisions; row++) {
  25920. for (col = 0; col <= options.subdivisions; col++) {
  25921. 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));
  25922. // Compute height
  25923. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25924. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25925. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25926. var r = options.buffer[pos] / 255.0;
  25927. var g = options.buffer[pos + 1] / 255.0;
  25928. var b = options.buffer[pos + 2] / 255.0;
  25929. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25930. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25931. // Add vertex
  25932. positions.push(position.x, position.y, position.z);
  25933. normals.push(0, 0, 0);
  25934. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25935. }
  25936. }
  25937. // Indices
  25938. for (row = 0; row < options.subdivisions; row++) {
  25939. for (col = 0; col < options.subdivisions; col++) {
  25940. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25941. indices.push(col + 1 + row * (options.subdivisions + 1));
  25942. indices.push(col + row * (options.subdivisions + 1));
  25943. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25944. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25945. indices.push(col + row * (options.subdivisions + 1));
  25946. }
  25947. }
  25948. // Normals
  25949. VertexData.ComputeNormals(positions, indices, normals);
  25950. // Result
  25951. var vertexData = new VertexData();
  25952. vertexData.indices = indices;
  25953. vertexData.positions = positions;
  25954. vertexData.normals = normals;
  25955. vertexData.uvs = uvs;
  25956. return vertexData;
  25957. };
  25958. /**
  25959. * Creates the VertexData of the Plane.
  25960. */
  25961. VertexData.CreatePlane = function (options) {
  25962. var indices = [];
  25963. var positions = [];
  25964. var normals = [];
  25965. var uvs = [];
  25966. var width = options.width || options.size || 1;
  25967. var height = options.height || options.size || 1;
  25968. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25969. // Vertices
  25970. var halfWidth = width / 2.0;
  25971. var halfHeight = height / 2.0;
  25972. positions.push(-halfWidth, -halfHeight, 0);
  25973. normals.push(0, 0, -1.0);
  25974. uvs.push(0.0, 0.0);
  25975. positions.push(halfWidth, -halfHeight, 0);
  25976. normals.push(0, 0, -1.0);
  25977. uvs.push(1.0, 0.0);
  25978. positions.push(halfWidth, halfHeight, 0);
  25979. normals.push(0, 0, -1.0);
  25980. uvs.push(1.0, 1.0);
  25981. positions.push(-halfWidth, halfHeight, 0);
  25982. normals.push(0, 0, -1.0);
  25983. uvs.push(0.0, 1.0);
  25984. // Indices
  25985. indices.push(0);
  25986. indices.push(1);
  25987. indices.push(2);
  25988. indices.push(0);
  25989. indices.push(2);
  25990. indices.push(3);
  25991. // Sides
  25992. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25993. // Result
  25994. var vertexData = new VertexData();
  25995. vertexData.indices = indices;
  25996. vertexData.positions = positions;
  25997. vertexData.normals = normals;
  25998. vertexData.uvs = uvs;
  25999. return vertexData;
  26000. };
  26001. /**
  26002. * Creates the VertexData of the Disc or regular Polygon.
  26003. */
  26004. VertexData.CreateDisc = function (options) {
  26005. var positions = [];
  26006. var indices = [];
  26007. var normals = [];
  26008. var uvs = [];
  26009. var radius = options.radius || 0.5;
  26010. var tessellation = options.tessellation || 64;
  26011. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26013. // positions and uvs
  26014. positions.push(0, 0, 0); // disc center first
  26015. uvs.push(0.5, 0.5);
  26016. var theta = Math.PI * 2 * arc;
  26017. var step = theta / tessellation;
  26018. for (var a = 0; a < theta; a += step) {
  26019. var x = Math.cos(a);
  26020. var y = Math.sin(a);
  26021. var u = (x + 1) / 2;
  26022. var v = (1 - y) / 2;
  26023. positions.push(radius * x, radius * y, 0);
  26024. uvs.push(u, v);
  26025. }
  26026. if (arc === 1) {
  26027. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26028. uvs.push(uvs[2], uvs[3]);
  26029. }
  26030. //indices
  26031. var vertexNb = positions.length / 3;
  26032. for (var i = 1; i < vertexNb - 1; i++) {
  26033. indices.push(i + 1, 0, i);
  26034. }
  26035. // result
  26036. VertexData.ComputeNormals(positions, indices, normals);
  26037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26038. var vertexData = new VertexData();
  26039. vertexData.indices = indices;
  26040. vertexData.positions = positions;
  26041. vertexData.normals = normals;
  26042. vertexData.uvs = uvs;
  26043. return vertexData;
  26044. };
  26045. /**
  26046. * Re-creates the VertexData of the Polygon for sideOrientation.
  26047. */
  26048. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26049. var faceUV = fUV || new Array(3);
  26050. var faceColors = fColors;
  26051. var colors = [];
  26052. // default face colors and UV if undefined
  26053. for (var f = 0; f < 3; f++) {
  26054. if (faceUV[f] === undefined) {
  26055. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26056. }
  26057. if (faceColors && faceColors[f] === undefined) {
  26058. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26059. }
  26060. }
  26061. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26062. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26063. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26064. var indices = polygon.getIndices();
  26065. // set face colours and textures
  26066. var idx = 0;
  26067. var face = 0;
  26068. for (var index = 0; index < normals.length; index += 3) {
  26069. //Edge Face no. 1
  26070. if (Math.abs(normals[index + 1]) == 0) {
  26071. face = 1;
  26072. }
  26073. //Top Face no. 0
  26074. if (normals[index + 1] == 1) {
  26075. face = 0;
  26076. }
  26077. //Bottom Face no. 2
  26078. if (normals[index + 1] == -1) {
  26079. face = 2;
  26080. }
  26081. idx = index / 3;
  26082. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26083. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26084. if (faceColors) {
  26085. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26086. }
  26087. }
  26088. // sides
  26089. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26090. // Result
  26091. var vertexData = new VertexData();
  26092. vertexData.indices = indices;
  26093. vertexData.positions = positions;
  26094. vertexData.normals = normals;
  26095. vertexData.uvs = uvs;
  26096. if (faceColors) {
  26097. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26098. vertexData.colors = totalColors;
  26099. }
  26100. return vertexData;
  26101. };
  26102. /**
  26103. * Creates the VertexData of the IcoSphere.
  26104. */
  26105. VertexData.CreateIcoSphere = function (options) {
  26106. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26107. var radius = options.radius || 1;
  26108. var flat = (options.flat === undefined) ? true : options.flat;
  26109. var subdivisions = options.subdivisions || 4;
  26110. var radiusX = options.radiusX || radius;
  26111. var radiusY = options.radiusY || radius;
  26112. var radiusZ = options.radiusZ || radius;
  26113. var t = (1 + Math.sqrt(5)) / 2;
  26114. // 12 vertex x,y,z
  26115. var ico_vertices = [
  26116. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26117. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26118. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26119. ];
  26120. // index of 3 vertex makes a face of icopshere
  26121. var ico_indices = [
  26122. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26123. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26124. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26125. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26126. ];
  26127. // vertex for uv have aliased position, not for UV
  26128. var vertices_unalias_id = [
  26129. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26130. // vertex alias
  26131. 0,
  26132. 2,
  26133. 3,
  26134. 3,
  26135. 3,
  26136. 4,
  26137. 7,
  26138. 8,
  26139. 9,
  26140. 9,
  26141. 10,
  26142. 11 // 23: B + 12
  26143. ];
  26144. // uv as integer step (not pixels !)
  26145. var ico_vertexuv = [
  26146. 5, 1, 3, 1, 6, 4, 0, 0,
  26147. 5, 3, 4, 2, 2, 2, 4, 0,
  26148. 2, 0, 1, 1, 6, 0, 6, 2,
  26149. // vertex alias (for same vertex on different faces)
  26150. 0, 4,
  26151. 3, 3,
  26152. 4, 4,
  26153. 3, 1,
  26154. 4, 2,
  26155. 4, 4,
  26156. 0, 2,
  26157. 1, 1,
  26158. 2, 2,
  26159. 3, 3,
  26160. 1, 3,
  26161. 2, 4 // 23: B + 12
  26162. ];
  26163. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26164. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26165. // First island of uv mapping
  26166. // v = 4h 3+ 2
  26167. // v = 3h 9+ 4
  26168. // v = 2h 9+ 5 B
  26169. // v = 1h 9 1 0
  26170. // v = 0h 3 8 7 A
  26171. // u = 0 1 2 3 4 5 6 *a
  26172. // Second island of uv mapping
  26173. // v = 4h 0+ B+ 4+
  26174. // v = 3h A+ 2+
  26175. // v = 2h 7+ 6 3+
  26176. // v = 1h 8+ 3+
  26177. // v = 0h
  26178. // u = 0 1 2 3 4 5 6 *a
  26179. // Face layout on texture UV mapping
  26180. // ============
  26181. // \ 4 /\ 16 / ======
  26182. // \ / \ / /\ 11 /
  26183. // \/ 7 \/ / \ /
  26184. // ======= / 10 \/
  26185. // /\ 17 /\ =======
  26186. // / \ / \ \ 15 /\
  26187. // / 8 \/ 12 \ \ / \
  26188. // ============ \/ 6 \
  26189. // \ 18 /\ ============
  26190. // \ / \ \ 5 /\ 0 /
  26191. // \/ 13 \ \ / \ /
  26192. // ======= \/ 1 \/
  26193. // =============
  26194. // /\ 19 /\ 2 /\
  26195. // / \ / \ / \
  26196. // / 14 \/ 9 \/ 3 \
  26197. // ===================
  26198. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26199. var ustep = 138 / 1024;
  26200. var vstep = 239 / 1024;
  26201. var uoffset = 60 / 1024;
  26202. var voffset = 26 / 1024;
  26203. // Second island should have margin, not to touch the first island
  26204. // avoid any borderline artefact in pixel rounding
  26205. var island_u_offset = -40 / 1024;
  26206. var island_v_offset = +20 / 1024;
  26207. // face is either island 0 or 1 :
  26208. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26209. var island = [
  26210. 0, 0, 0, 0, 1,
  26211. 0, 0, 1, 1, 0,
  26212. 0, 0, 1, 1, 0,
  26213. 0, 1, 1, 1, 0 // 15 - 19
  26214. ];
  26215. var indices = [];
  26216. var positions = [];
  26217. var normals = [];
  26218. var uvs = [];
  26219. var current_indice = 0;
  26220. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26221. var face_vertex_pos = new Array(3);
  26222. var face_vertex_uv = new Array(3);
  26223. var v012;
  26224. for (v012 = 0; v012 < 3; v012++) {
  26225. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26226. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26227. }
  26228. // create all with normals
  26229. for (var face = 0; face < 20; face++) {
  26230. // 3 vertex per face
  26231. for (v012 = 0; v012 < 3; v012++) {
  26232. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26233. var v_id = ico_indices[3 * face + v012];
  26234. // vertex have 3D position (x,y,z)
  26235. 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]);
  26236. // Normalize to get normal, then scale to radius
  26237. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26238. // uv Coordinates from vertex ID
  26239. 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);
  26240. }
  26241. // Subdivide the face (interpolate pos, norm, uv)
  26242. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26243. // - norm is linear interpolation of vertex corner normal
  26244. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26245. // - uv is linear interpolation
  26246. //
  26247. // Topology is as below for sub-divide by 2
  26248. // vertex shown as v0,v1,v2
  26249. // interp index is i1 to progress in range [v0,v1[
  26250. // interp index is i2 to progress in range [v0,v2[
  26251. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26252. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26253. //
  26254. //
  26255. // i2 v2
  26256. // ^ ^
  26257. // / / \
  26258. // / / \
  26259. // / / \
  26260. // / / (0,1) \
  26261. // / #---------\
  26262. // / / \ (0,0)'/ \
  26263. // / / \ / \
  26264. // / / \ / \
  26265. // / / (0,0) \ / (1,0) \
  26266. // / #---------#---------\
  26267. // v0 v1
  26268. //
  26269. // --------------------> i1
  26270. //
  26271. // interp of (i1,i2):
  26272. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26273. // along i1 : lerp(x0,x1, i1/(S-i2))
  26274. //
  26275. // centroid of triangle is needed to get help normal computation
  26276. // (c1,c2) are used for centroid location
  26277. var interp_vertex = function (i1, i2, c1, c2) {
  26278. // vertex is interpolated from
  26279. // - face_vertex_pos[0..2]
  26280. // - face_vertex_uv[0..2]
  26281. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26282. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26283. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26284. pos_interp.normalize();
  26285. var vertex_normal;
  26286. if (flat) {
  26287. // in flat mode, recalculate normal as face centroid normal
  26288. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26289. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26290. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26291. }
  26292. else {
  26293. // in smooth mode, recalculate normal from each single vertex position
  26294. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26295. }
  26296. // Vertex normal need correction due to X,Y,Z radius scaling
  26297. vertex_normal.x /= radiusX;
  26298. vertex_normal.y /= radiusY;
  26299. vertex_normal.z /= radiusZ;
  26300. vertex_normal.normalize();
  26301. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26302. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26303. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26304. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26305. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26306. uvs.push(uv_interp.x, uv_interp.y);
  26307. // push each vertex has member of a face
  26308. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26309. indices.push(current_indice);
  26310. current_indice++;
  26311. };
  26312. for (var i2 = 0; i2 < subdivisions; i2++) {
  26313. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26314. // face : (i1,i2) for /\ :
  26315. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26316. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26317. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26318. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26319. if (i1 + i2 + 1 < subdivisions) {
  26320. // face : (i1,i2)' for \/ :
  26321. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26322. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26323. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26324. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26325. }
  26326. }
  26327. }
  26328. }
  26329. // Sides
  26330. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26331. // Result
  26332. var vertexData = new VertexData();
  26333. vertexData.indices = indices;
  26334. vertexData.positions = positions;
  26335. vertexData.normals = normals;
  26336. vertexData.uvs = uvs;
  26337. return vertexData;
  26338. };
  26339. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26340. /**
  26341. * Creates the VertexData of the Polyhedron.
  26342. */
  26343. VertexData.CreatePolyhedron = function (options) {
  26344. // provided polyhedron types :
  26345. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26346. // 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)
  26347. var polyhedra = [];
  26348. 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]] };
  26349. 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]] };
  26350. polyhedra[2] = {
  26351. 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]],
  26352. 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]]
  26353. };
  26354. polyhedra[3] = {
  26355. 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]],
  26356. 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]]
  26357. };
  26358. polyhedra[4] = {
  26359. 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]],
  26360. 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]]
  26361. };
  26362. 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]] };
  26363. 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]] };
  26364. 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]] };
  26365. 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]] };
  26366. 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]] };
  26367. 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]] };
  26368. 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]] };
  26369. 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]] };
  26370. 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]] };
  26371. polyhedra[14] = {
  26372. 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]],
  26373. 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]]
  26374. };
  26375. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26376. var size = options.size;
  26377. var sizeX = options.sizeX || size || 1;
  26378. var sizeY = options.sizeY || size || 1;
  26379. var sizeZ = options.sizeZ || size || 1;
  26380. var data = options.custom || polyhedra[type];
  26381. var nbfaces = data.face.length;
  26382. var faceUV = options.faceUV || new Array(nbfaces);
  26383. var faceColors = options.faceColors;
  26384. var flat = (options.flat === undefined) ? true : options.flat;
  26385. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26386. var positions = [];
  26387. var indices = [];
  26388. var normals = [];
  26389. var uvs = [];
  26390. var colors = [];
  26391. var index = 0;
  26392. var faceIdx = 0; // face cursor in the array "indexes"
  26393. var indexes = [];
  26394. var i = 0;
  26395. var f = 0;
  26396. var u, v, ang, x, y, tmp;
  26397. // default face colors and UV if undefined
  26398. if (flat) {
  26399. for (f = 0; f < nbfaces; f++) {
  26400. if (faceColors && faceColors[f] === undefined) {
  26401. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26402. }
  26403. if (faceUV && faceUV[f] === undefined) {
  26404. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26405. }
  26406. }
  26407. }
  26408. if (!flat) {
  26409. for (i = 0; i < data.vertex.length; i++) {
  26410. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26411. uvs.push(0, 0);
  26412. }
  26413. for (f = 0; f < nbfaces; f++) {
  26414. for (i = 0; i < data.face[f].length - 2; i++) {
  26415. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26416. }
  26417. }
  26418. }
  26419. else {
  26420. for (f = 0; f < nbfaces; f++) {
  26421. var fl = data.face[f].length; // number of vertices of the current face
  26422. ang = 2 * Math.PI / fl;
  26423. x = 0.5 * Math.tan(ang / 2);
  26424. y = 0.5;
  26425. // positions, uvs, colors
  26426. for (i = 0; i < fl; i++) {
  26427. // positions
  26428. 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);
  26429. indexes.push(index);
  26430. index++;
  26431. // uvs
  26432. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26433. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26434. uvs.push(u, v);
  26435. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26436. y = x * Math.sin(ang) + y * Math.cos(ang);
  26437. x = tmp;
  26438. // colors
  26439. if (faceColors) {
  26440. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26441. }
  26442. }
  26443. // indices from indexes
  26444. for (i = 0; i < fl - 2; i++) {
  26445. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26446. }
  26447. faceIdx += fl;
  26448. }
  26449. }
  26450. VertexData.ComputeNormals(positions, indices, normals);
  26451. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26452. var vertexData = new VertexData();
  26453. vertexData.positions = positions;
  26454. vertexData.indices = indices;
  26455. vertexData.normals = normals;
  26456. vertexData.uvs = uvs;
  26457. if (faceColors && flat) {
  26458. vertexData.colors = colors;
  26459. }
  26460. return vertexData;
  26461. };
  26462. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26463. /**
  26464. * Creates the VertexData of the Torus Knot.
  26465. */
  26466. VertexData.CreateTorusKnot = function (options) {
  26467. var indices = [];
  26468. var positions = [];
  26469. var normals = [];
  26470. var uvs = [];
  26471. var radius = options.radius || 2;
  26472. var tube = options.tube || 0.5;
  26473. var radialSegments = options.radialSegments || 32;
  26474. var tubularSegments = options.tubularSegments || 32;
  26475. var p = options.p || 2;
  26476. var q = options.q || 3;
  26477. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26478. // Helper
  26479. var getPos = function (angle) {
  26480. var cu = Math.cos(angle);
  26481. var su = Math.sin(angle);
  26482. var quOverP = q / p * angle;
  26483. var cs = Math.cos(quOverP);
  26484. var tx = radius * (2 + cs) * 0.5 * cu;
  26485. var ty = radius * (2 + cs) * su * 0.5;
  26486. var tz = radius * Math.sin(quOverP) * 0.5;
  26487. return new BABYLON.Vector3(tx, ty, tz);
  26488. };
  26489. // Vertices
  26490. var i;
  26491. var j;
  26492. for (i = 0; i <= radialSegments; i++) {
  26493. var modI = i % radialSegments;
  26494. var u = modI / radialSegments * 2 * p * Math.PI;
  26495. var p1 = getPos(u);
  26496. var p2 = getPos(u + 0.01);
  26497. var tang = p2.subtract(p1);
  26498. var n = p2.add(p1);
  26499. var bitan = BABYLON.Vector3.Cross(tang, n);
  26500. n = BABYLON.Vector3.Cross(bitan, tang);
  26501. bitan.normalize();
  26502. n.normalize();
  26503. for (j = 0; j < tubularSegments; j++) {
  26504. var modJ = j % tubularSegments;
  26505. var v = modJ / tubularSegments * 2 * Math.PI;
  26506. var cx = -tube * Math.cos(v);
  26507. var cy = tube * Math.sin(v);
  26508. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26509. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26510. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26511. uvs.push(i / radialSegments);
  26512. uvs.push(j / tubularSegments);
  26513. }
  26514. }
  26515. for (i = 0; i < radialSegments; i++) {
  26516. for (j = 0; j < tubularSegments; j++) {
  26517. var jNext = (j + 1) % tubularSegments;
  26518. var a = i * tubularSegments + j;
  26519. var b = (i + 1) * tubularSegments + j;
  26520. var c = (i + 1) * tubularSegments + jNext;
  26521. var d = i * tubularSegments + jNext;
  26522. indices.push(d);
  26523. indices.push(b);
  26524. indices.push(a);
  26525. indices.push(d);
  26526. indices.push(c);
  26527. indices.push(b);
  26528. }
  26529. }
  26530. // Normals
  26531. VertexData.ComputeNormals(positions, indices, normals);
  26532. // Sides
  26533. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26534. // Result
  26535. var vertexData = new VertexData();
  26536. vertexData.indices = indices;
  26537. vertexData.positions = positions;
  26538. vertexData.normals = normals;
  26539. vertexData.uvs = uvs;
  26540. return vertexData;
  26541. };
  26542. // Tools
  26543. /**
  26544. * @param {any} - positions (number[] or Float32Array)
  26545. * @param {any} - indices (number[] or Uint16Array)
  26546. * @param {any} - normals (number[] or Float32Array)
  26547. * options (optional) :
  26548. * facetPositions : optional array of facet positions (vector3)
  26549. * facetNormals : optional array of facet normals (vector3)
  26550. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26551. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26552. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26553. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26554. * bInfo : optional bounding info, required for facetPartitioning computation
  26555. */
  26556. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26557. // temporary scalar variables
  26558. var index = 0; // facet index
  26559. var p1p2x = 0.0; // p1p2 vector x coordinate
  26560. var p1p2y = 0.0; // p1p2 vector y coordinate
  26561. var p1p2z = 0.0; // p1p2 vector z coordinate
  26562. var p3p2x = 0.0; // p3p2 vector x coordinate
  26563. var p3p2y = 0.0; // p3p2 vector y coordinate
  26564. var p3p2z = 0.0; // p3p2 vector z coordinate
  26565. var faceNormalx = 0.0; // facet normal x coordinate
  26566. var faceNormaly = 0.0; // facet normal y coordinate
  26567. var faceNormalz = 0.0; // facet normal z coordinate
  26568. var length = 0.0; // facet normal length before normalization
  26569. var v1x = 0; // vector1 x index in the positions array
  26570. var v1y = 0; // vector1 y index in the positions array
  26571. var v1z = 0; // vector1 z index in the positions array
  26572. var v2x = 0; // vector2 x index in the positions array
  26573. var v2y = 0; // vector2 y index in the positions array
  26574. var v2z = 0; // vector2 z index in the positions array
  26575. var v3x = 0; // vector3 x index in the positions array
  26576. var v3y = 0; // vector3 y index in the positions array
  26577. var v3z = 0; // vector3 z index in the positions array
  26578. var computeFacetNormals = false;
  26579. var computeFacetPositions = false;
  26580. var computeFacetPartitioning = false;
  26581. var faceNormalSign = 1;
  26582. if (options) {
  26583. computeFacetNormals = (options.facetNormals) ? true : false;
  26584. computeFacetPositions = (options.facetPositions) ? true : false;
  26585. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26586. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26587. }
  26588. // facetPartitioning reinit if needed
  26589. if (computeFacetPartitioning) {
  26590. var ox = 0; // X partitioning index for facet position
  26591. var oy = 0; // Y partinioning index for facet position
  26592. var oz = 0; // Z partinioning index for facet position
  26593. var b1x = 0; // X partitioning index for facet v1 vertex
  26594. var b1y = 0; // Y partitioning index for facet v1 vertex
  26595. var b1z = 0; // z partitioning index for facet v1 vertex
  26596. var b2x = 0; // X partitioning index for facet v2 vertex
  26597. var b2y = 0; // Y partitioning index for facet v2 vertex
  26598. var b2z = 0; // Z partitioning index for facet v2 vertex
  26599. var b3x = 0; // X partitioning index for facet v3 vertex
  26600. var b3y = 0; // Y partitioning index for facet v3 vertex
  26601. var b3z = 0; // Z partitioning index for facet v3 vertex
  26602. var block_idx_o = 0; // facet barycenter block index
  26603. var block_idx_v1 = 0; // v1 vertex block index
  26604. var block_idx_v2 = 0; // v2 vertex block index
  26605. var block_idx_v3 = 0; // v3 vertex block index
  26606. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26607. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26608. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26609. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26610. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26611. var subSq = options.subDiv.max * options.subDiv.max;
  26612. options.facetPartitioning.length = 0;
  26613. }
  26614. // reset the normals
  26615. for (index = 0; index < positions.length; index++) {
  26616. normals[index] = 0.0;
  26617. }
  26618. // Loop : 1 indice triplet = 1 facet
  26619. var nbFaces = indices.length / 3;
  26620. for (index = 0; index < nbFaces; index++) {
  26621. // get the indexes of the coordinates of each vertex of the facet
  26622. v1x = indices[index * 3] * 3;
  26623. v1y = v1x + 1;
  26624. v1z = v1x + 2;
  26625. v2x = indices[index * 3 + 1] * 3;
  26626. v2y = v2x + 1;
  26627. v2z = v2x + 2;
  26628. v3x = indices[index * 3 + 2] * 3;
  26629. v3y = v3x + 1;
  26630. v3z = v3x + 2;
  26631. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26632. p1p2y = positions[v1y] - positions[v2y];
  26633. p1p2z = positions[v1z] - positions[v2z];
  26634. p3p2x = positions[v3x] - positions[v2x];
  26635. p3p2y = positions[v3y] - positions[v2y];
  26636. p3p2z = positions[v3z] - positions[v2z];
  26637. // compute the face normal with the cross product
  26638. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26639. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26640. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26641. // normalize this normal and store it in the array facetData
  26642. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26643. length = (length === 0) ? 1.0 : length;
  26644. faceNormalx /= length;
  26645. faceNormaly /= length;
  26646. faceNormalz /= length;
  26647. if (computeFacetNormals) {
  26648. options.facetNormals[index].x = faceNormalx;
  26649. options.facetNormals[index].y = faceNormaly;
  26650. options.facetNormals[index].z = faceNormalz;
  26651. }
  26652. if (computeFacetPositions) {
  26653. // compute and the facet barycenter coordinates in the array facetPositions
  26654. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26655. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26656. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26657. }
  26658. if (computeFacetPartitioning) {
  26659. // store the facet indexes in arrays in the main facetPartitioning array :
  26660. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26661. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26662. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26663. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26664. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26665. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26666. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26667. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26668. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26669. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26670. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26671. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26672. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26673. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26674. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26675. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26676. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26677. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26678. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26679. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26680. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26681. // push each facet index in each block containing the vertex
  26682. options.facetPartitioning[block_idx_v1].push(index);
  26683. if (block_idx_v2 != block_idx_v1) {
  26684. options.facetPartitioning[block_idx_v2].push(index);
  26685. }
  26686. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26687. options.facetPartitioning[block_idx_v3].push(index);
  26688. }
  26689. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26690. options.facetPartitioning[block_idx_o].push(index);
  26691. }
  26692. }
  26693. // compute the normals anyway
  26694. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26695. normals[v1y] += faceNormaly;
  26696. normals[v1z] += faceNormalz;
  26697. normals[v2x] += faceNormalx;
  26698. normals[v2y] += faceNormaly;
  26699. normals[v2z] += faceNormalz;
  26700. normals[v3x] += faceNormalx;
  26701. normals[v3y] += faceNormaly;
  26702. normals[v3z] += faceNormalz;
  26703. }
  26704. // last normalization of each normal
  26705. for (index = 0; index < normals.length / 3; index++) {
  26706. faceNormalx = normals[index * 3];
  26707. faceNormaly = normals[index * 3 + 1];
  26708. faceNormalz = normals[index * 3 + 2];
  26709. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26710. length = (length === 0) ? 1.0 : length;
  26711. faceNormalx /= length;
  26712. faceNormaly /= length;
  26713. faceNormalz /= length;
  26714. normals[index * 3] = faceNormalx;
  26715. normals[index * 3 + 1] = faceNormaly;
  26716. normals[index * 3 + 2] = faceNormalz;
  26717. }
  26718. };
  26719. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26720. var li = indices.length;
  26721. var ln = normals.length;
  26722. var i;
  26723. var n;
  26724. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26725. switch (sideOrientation) {
  26726. case BABYLON.Mesh.FRONTSIDE:
  26727. // nothing changed
  26728. break;
  26729. case BABYLON.Mesh.BACKSIDE:
  26730. var tmp;
  26731. // indices
  26732. for (i = 0; i < li; i += 3) {
  26733. tmp = indices[i];
  26734. indices[i] = indices[i + 2];
  26735. indices[i + 2] = tmp;
  26736. }
  26737. // normals
  26738. for (n = 0; n < ln; n++) {
  26739. normals[n] = -normals[n];
  26740. }
  26741. break;
  26742. case BABYLON.Mesh.DOUBLESIDE:
  26743. // positions
  26744. var lp = positions.length;
  26745. var l = lp / 3;
  26746. for (var p = 0; p < lp; p++) {
  26747. positions[lp + p] = positions[p];
  26748. }
  26749. // indices
  26750. for (i = 0; i < li; i += 3) {
  26751. indices[i + li] = indices[i + 2] + l;
  26752. indices[i + 1 + li] = indices[i + 1] + l;
  26753. indices[i + 2 + li] = indices[i] + l;
  26754. }
  26755. // normals
  26756. for (n = 0; n < ln; n++) {
  26757. normals[ln + n] = -normals[n];
  26758. }
  26759. // uvs
  26760. var lu = uvs.length;
  26761. var u = 0;
  26762. for (u = 0; u < lu; u++) {
  26763. uvs[u + lu] = uvs[u];
  26764. }
  26765. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26766. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26767. u = 0;
  26768. for (i = 0; i < lu / 2; i++) {
  26769. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26770. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26771. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26772. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26773. u += 2;
  26774. }
  26775. break;
  26776. }
  26777. };
  26778. /**
  26779. * Creates a new VertexData from the imported parameters.
  26780. */
  26781. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26782. var vertexData = new VertexData();
  26783. // positions
  26784. var positions = parsedVertexData.positions;
  26785. if (positions) {
  26786. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26787. }
  26788. // normals
  26789. var normals = parsedVertexData.normals;
  26790. if (normals) {
  26791. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26792. }
  26793. // tangents
  26794. var tangents = parsedVertexData.tangents;
  26795. if (tangents) {
  26796. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26797. }
  26798. // uvs
  26799. var uvs = parsedVertexData.uvs;
  26800. if (uvs) {
  26801. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26802. }
  26803. // uv2s
  26804. var uv2s = parsedVertexData.uv2s;
  26805. if (uv2s) {
  26806. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26807. }
  26808. // uv3s
  26809. var uv3s = parsedVertexData.uv3s;
  26810. if (uv3s) {
  26811. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26812. }
  26813. // uv4s
  26814. var uv4s = parsedVertexData.uv4s;
  26815. if (uv4s) {
  26816. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26817. }
  26818. // uv5s
  26819. var uv5s = parsedVertexData.uv5s;
  26820. if (uv5s) {
  26821. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26822. }
  26823. // uv6s
  26824. var uv6s = parsedVertexData.uv6s;
  26825. if (uv6s) {
  26826. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26827. }
  26828. // colors
  26829. var colors = parsedVertexData.colors;
  26830. if (colors) {
  26831. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26832. }
  26833. // matricesIndices
  26834. var matricesIndices = parsedVertexData.matricesIndices;
  26835. if (matricesIndices) {
  26836. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26837. }
  26838. // matricesWeights
  26839. var matricesWeights = parsedVertexData.matricesWeights;
  26840. if (matricesWeights) {
  26841. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26842. }
  26843. // indices
  26844. var indices = parsedVertexData.indices;
  26845. if (indices) {
  26846. vertexData.indices = indices;
  26847. }
  26848. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26849. };
  26850. return VertexData;
  26851. }());
  26852. BABYLON.VertexData = VertexData;
  26853. })(BABYLON || (BABYLON = {}));
  26854. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26855. var BABYLON;
  26856. (function (BABYLON) {
  26857. var Geometry = (function () {
  26858. function Geometry(id, scene, vertexData, updatable, mesh) {
  26859. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26860. this._totalVertices = 0;
  26861. this._isDisposed = false;
  26862. this.id = id;
  26863. this._engine = scene.getEngine();
  26864. this._meshes = [];
  26865. this._scene = scene;
  26866. //Init vertex buffer cache
  26867. this._vertexBuffers = {};
  26868. this._indices = [];
  26869. // vertexData
  26870. if (vertexData) {
  26871. this.setAllVerticesData(vertexData, updatable);
  26872. }
  26873. else {
  26874. this._totalVertices = 0;
  26875. this._indices = [];
  26876. }
  26877. if (this._engine.getCaps().vertexArrayObject) {
  26878. this._vertexArrayObjects = {};
  26879. }
  26880. // applyToMesh
  26881. if (mesh) {
  26882. if (mesh.getClassName() === "LinesMesh") {
  26883. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26884. this.updateExtend();
  26885. }
  26886. this.applyToMesh(mesh);
  26887. mesh.computeWorldMatrix(true);
  26888. }
  26889. }
  26890. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26891. /**
  26892. * 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
  26893. * @returns The Bias Vector
  26894. */
  26895. get: function () {
  26896. return this._boundingBias;
  26897. },
  26898. set: function (value) {
  26899. if (this._boundingBias && this._boundingBias.equals(value)) {
  26900. return;
  26901. }
  26902. this._boundingBias = value.clone();
  26903. this.updateBoundingInfo(true, null);
  26904. },
  26905. enumerable: true,
  26906. configurable: true
  26907. });
  26908. Object.defineProperty(Geometry.prototype, "extend", {
  26909. get: function () {
  26910. return this._extend;
  26911. },
  26912. enumerable: true,
  26913. configurable: true
  26914. });
  26915. Geometry.prototype.getScene = function () {
  26916. return this._scene;
  26917. };
  26918. Geometry.prototype.getEngine = function () {
  26919. return this._engine;
  26920. };
  26921. Geometry.prototype.isReady = function () {
  26922. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26923. };
  26924. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26925. get: function () {
  26926. for (var index = 0; index < this._meshes.length; index++) {
  26927. if (!this._meshes[index].doNotSerialize) {
  26928. return false;
  26929. }
  26930. }
  26931. return true;
  26932. },
  26933. enumerable: true,
  26934. configurable: true
  26935. });
  26936. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26937. vertexData.applyToGeometry(this, updatable);
  26938. this.notifyUpdate();
  26939. };
  26940. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26941. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26942. this.setVerticesBuffer(buffer);
  26943. };
  26944. Geometry.prototype.removeVerticesData = function (kind) {
  26945. if (this._vertexBuffers[kind]) {
  26946. this._vertexBuffers[kind].dispose();
  26947. delete this._vertexBuffers[kind];
  26948. }
  26949. };
  26950. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26951. var kind = buffer.getKind();
  26952. if (this._vertexBuffers[kind]) {
  26953. this._vertexBuffers[kind].dispose();
  26954. }
  26955. this._vertexBuffers[kind] = buffer;
  26956. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26957. var data = buffer.getData();
  26958. var stride = buffer.getStrideSize();
  26959. this._totalVertices = data.length / stride;
  26960. this.updateExtend(data, stride);
  26961. this._resetPointsArrayCache();
  26962. var meshes = this._meshes;
  26963. var numOfMeshes = meshes.length;
  26964. for (var index = 0; index < numOfMeshes; index++) {
  26965. var mesh = meshes[index];
  26966. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26967. mesh._createGlobalSubMesh();
  26968. mesh.computeWorldMatrix(true);
  26969. }
  26970. }
  26971. this.notifyUpdate(kind);
  26972. if (this._vertexArrayObjects) {
  26973. this._disposeVertexArrayObjects();
  26974. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26975. }
  26976. };
  26977. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26978. var vertexBuffer = this.getVertexBuffer(kind);
  26979. if (!vertexBuffer) {
  26980. return;
  26981. }
  26982. vertexBuffer.updateDirectly(data, offset);
  26983. this.notifyUpdate(kind);
  26984. };
  26985. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26986. var vertexBuffer = this.getVertexBuffer(kind);
  26987. if (!vertexBuffer) {
  26988. return;
  26989. }
  26990. vertexBuffer.update(data);
  26991. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26992. var stride = vertexBuffer.getStrideSize();
  26993. this._totalVertices = data.length / stride;
  26994. this.updateBoundingInfo(updateExtends, data);
  26995. }
  26996. this.notifyUpdate(kind);
  26997. };
  26998. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26999. if (updateExtends) {
  27000. this.updateExtend(data);
  27001. }
  27002. var meshes = this._meshes;
  27003. var numOfMeshes = meshes.length;
  27004. this._resetPointsArrayCache();
  27005. for (var index = 0; index < numOfMeshes; index++) {
  27006. var mesh = meshes[index];
  27007. if (updateExtends) {
  27008. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27009. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27010. var subMesh = mesh.subMeshes[subIndex];
  27011. subMesh.refreshBoundingInfo();
  27012. }
  27013. }
  27014. }
  27015. };
  27016. Geometry.prototype._bind = function (effect, indexToBind) {
  27017. if (indexToBind === void 0) { indexToBind = undefined; }
  27018. if (indexToBind === undefined) {
  27019. indexToBind = this._indexBuffer;
  27020. }
  27021. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27022. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27023. return;
  27024. }
  27025. // Using VAO
  27026. if (!this._vertexArrayObjects[effect.key]) {
  27027. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27028. }
  27029. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27030. };
  27031. Geometry.prototype.getTotalVertices = function () {
  27032. if (!this.isReady()) {
  27033. return 0;
  27034. }
  27035. return this._totalVertices;
  27036. };
  27037. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27038. var vertexBuffer = this.getVertexBuffer(kind);
  27039. if (!vertexBuffer) {
  27040. return null;
  27041. }
  27042. var orig = vertexBuffer.getData();
  27043. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27044. return orig;
  27045. }
  27046. else {
  27047. var len = orig.length;
  27048. var copy = [];
  27049. for (var i = 0; i < len; i++) {
  27050. copy.push(orig[i]);
  27051. }
  27052. return copy;
  27053. }
  27054. };
  27055. Geometry.prototype.getVertexBuffer = function (kind) {
  27056. if (!this.isReady()) {
  27057. return null;
  27058. }
  27059. return this._vertexBuffers[kind];
  27060. };
  27061. Geometry.prototype.getVertexBuffers = function () {
  27062. if (!this.isReady()) {
  27063. return null;
  27064. }
  27065. return this._vertexBuffers;
  27066. };
  27067. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27068. if (!this._vertexBuffers) {
  27069. if (this._delayInfo) {
  27070. return this._delayInfo.indexOf(kind) !== -1;
  27071. }
  27072. return false;
  27073. }
  27074. return this._vertexBuffers[kind] !== undefined;
  27075. };
  27076. Geometry.prototype.getVerticesDataKinds = function () {
  27077. var result = [];
  27078. var kind;
  27079. if (!this._vertexBuffers && this._delayInfo) {
  27080. for (kind in this._delayInfo) {
  27081. result.push(kind);
  27082. }
  27083. }
  27084. else {
  27085. for (kind in this._vertexBuffers) {
  27086. result.push(kind);
  27087. }
  27088. }
  27089. return result;
  27090. };
  27091. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27092. if (this._indexBuffer) {
  27093. this._engine._releaseBuffer(this._indexBuffer);
  27094. }
  27095. this._disposeVertexArrayObjects();
  27096. this._indices = indices;
  27097. if (this._meshes.length !== 0 && this._indices) {
  27098. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27099. }
  27100. if (totalVertices !== undefined) {
  27101. this._totalVertices = totalVertices;
  27102. }
  27103. var meshes = this._meshes;
  27104. var numOfMeshes = meshes.length;
  27105. for (var index = 0; index < numOfMeshes; index++) {
  27106. meshes[index]._createGlobalSubMesh();
  27107. }
  27108. this.notifyUpdate();
  27109. };
  27110. Geometry.prototype.getTotalIndices = function () {
  27111. if (!this.isReady()) {
  27112. return 0;
  27113. }
  27114. return this._indices.length;
  27115. };
  27116. Geometry.prototype.getIndices = function (copyWhenShared) {
  27117. if (!this.isReady()) {
  27118. return null;
  27119. }
  27120. var orig = this._indices;
  27121. if (!copyWhenShared || this._meshes.length === 1) {
  27122. return orig;
  27123. }
  27124. else {
  27125. var len = orig.length;
  27126. var copy = [];
  27127. for (var i = 0; i < len; i++) {
  27128. copy.push(orig[i]);
  27129. }
  27130. return copy;
  27131. }
  27132. };
  27133. Geometry.prototype.getIndexBuffer = function () {
  27134. if (!this.isReady()) {
  27135. return null;
  27136. }
  27137. return this._indexBuffer;
  27138. };
  27139. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27140. if (!effect || !this._vertexArrayObjects) {
  27141. return;
  27142. }
  27143. if (this._vertexArrayObjects[effect.key]) {
  27144. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27145. delete this._vertexArrayObjects[effect.key];
  27146. }
  27147. };
  27148. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27149. var meshes = this._meshes;
  27150. var index = meshes.indexOf(mesh);
  27151. if (index === -1) {
  27152. return;
  27153. }
  27154. meshes.splice(index, 1);
  27155. mesh._geometry = null;
  27156. if (meshes.length === 0 && shouldDispose) {
  27157. this.dispose();
  27158. }
  27159. };
  27160. Geometry.prototype.applyToMesh = function (mesh) {
  27161. if (mesh._geometry === this) {
  27162. return;
  27163. }
  27164. var previousGeometry = mesh._geometry;
  27165. if (previousGeometry) {
  27166. previousGeometry.releaseForMesh(mesh);
  27167. }
  27168. var meshes = this._meshes;
  27169. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27170. mesh._geometry = this;
  27171. this._scene.pushGeometry(this);
  27172. meshes.push(mesh);
  27173. if (this.isReady()) {
  27174. this._applyToMesh(mesh);
  27175. }
  27176. else {
  27177. mesh._boundingInfo = this._boundingInfo;
  27178. }
  27179. };
  27180. Geometry.prototype.updateExtend = function (data, stride) {
  27181. if (data === void 0) { data = null; }
  27182. if (!data) {
  27183. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27184. }
  27185. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27186. };
  27187. Geometry.prototype._applyToMesh = function (mesh) {
  27188. var numOfMeshes = this._meshes.length;
  27189. // vertexBuffers
  27190. for (var kind in this._vertexBuffers) {
  27191. if (numOfMeshes === 1) {
  27192. this._vertexBuffers[kind].create();
  27193. }
  27194. var buffer = this._vertexBuffers[kind].getBuffer();
  27195. if (buffer)
  27196. buffer.references = numOfMeshes;
  27197. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27198. if (!this._extend) {
  27199. this.updateExtend(this._vertexBuffers[kind].getData());
  27200. }
  27201. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27202. mesh._createGlobalSubMesh();
  27203. //bounding info was just created again, world matrix should be applied again.
  27204. mesh._updateBoundingInfo();
  27205. }
  27206. }
  27207. // indexBuffer
  27208. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27209. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27210. }
  27211. if (this._indexBuffer) {
  27212. this._indexBuffer.references = numOfMeshes;
  27213. }
  27214. };
  27215. Geometry.prototype.notifyUpdate = function (kind) {
  27216. if (this.onGeometryUpdated) {
  27217. this.onGeometryUpdated(this, kind);
  27218. }
  27219. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27220. var mesh = _a[_i];
  27221. mesh._markSubMeshesAsAttributesDirty();
  27222. }
  27223. };
  27224. Geometry.prototype.load = function (scene, onLoaded) {
  27225. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27226. return;
  27227. }
  27228. if (this.isReady()) {
  27229. if (onLoaded) {
  27230. onLoaded();
  27231. }
  27232. return;
  27233. }
  27234. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27235. this._queueLoad(scene, onLoaded);
  27236. };
  27237. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27238. var _this = this;
  27239. scene._addPendingData(this);
  27240. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27241. _this._delayLoadingFunction(JSON.parse(data), _this);
  27242. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27243. _this._delayInfo = [];
  27244. scene._removePendingData(_this);
  27245. var meshes = _this._meshes;
  27246. var numOfMeshes = meshes.length;
  27247. for (var index = 0; index < numOfMeshes; index++) {
  27248. _this._applyToMesh(meshes[index]);
  27249. }
  27250. if (onLoaded) {
  27251. onLoaded();
  27252. }
  27253. }, function () { }, scene.database);
  27254. };
  27255. /**
  27256. * Invert the geometry to move from a right handed system to a left handed one.
  27257. */
  27258. Geometry.prototype.toLeftHanded = function () {
  27259. // Flip faces
  27260. var tIndices = this.getIndices(false);
  27261. if (tIndices != null && tIndices.length > 0) {
  27262. for (var i = 0; i < tIndices.length; i += 3) {
  27263. var tTemp = tIndices[i + 0];
  27264. tIndices[i + 0] = tIndices[i + 2];
  27265. tIndices[i + 2] = tTemp;
  27266. }
  27267. this.setIndices(tIndices);
  27268. }
  27269. // Negate position.z
  27270. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27271. if (tPositions != null && tPositions.length > 0) {
  27272. for (var i = 0; i < tPositions.length; i += 3) {
  27273. tPositions[i + 2] = -tPositions[i + 2];
  27274. }
  27275. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27276. }
  27277. // Negate normal.z
  27278. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27279. if (tNormals != null && tNormals.length > 0) {
  27280. for (var i = 0; i < tNormals.length; i += 3) {
  27281. tNormals[i + 2] = -tNormals[i + 2];
  27282. }
  27283. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27284. }
  27285. };
  27286. // Cache
  27287. Geometry.prototype._resetPointsArrayCache = function () {
  27288. this._positions = null;
  27289. };
  27290. Geometry.prototype._generatePointsArray = function () {
  27291. if (this._positions)
  27292. return true;
  27293. this._positions = [];
  27294. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27295. if (!data) {
  27296. return false;
  27297. }
  27298. for (var index = 0; index < data.length; index += 3) {
  27299. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27300. }
  27301. return true;
  27302. };
  27303. Geometry.prototype.isDisposed = function () {
  27304. return this._isDisposed;
  27305. };
  27306. Geometry.prototype._disposeVertexArrayObjects = function () {
  27307. if (this._vertexArrayObjects) {
  27308. for (var kind in this._vertexArrayObjects) {
  27309. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27310. }
  27311. this._vertexArrayObjects = {};
  27312. }
  27313. };
  27314. Geometry.prototype.dispose = function () {
  27315. var meshes = this._meshes;
  27316. var numOfMeshes = meshes.length;
  27317. var index;
  27318. for (index = 0; index < numOfMeshes; index++) {
  27319. this.releaseForMesh(meshes[index]);
  27320. }
  27321. this._meshes = [];
  27322. this._disposeVertexArrayObjects();
  27323. for (var kind in this._vertexBuffers) {
  27324. this._vertexBuffers[kind].dispose();
  27325. }
  27326. this._vertexBuffers = {};
  27327. this._totalVertices = 0;
  27328. if (this._indexBuffer) {
  27329. this._engine._releaseBuffer(this._indexBuffer);
  27330. }
  27331. this._indexBuffer = null;
  27332. this._indices = [];
  27333. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27334. this.delayLoadingFile = null;
  27335. this._delayLoadingFunction = null;
  27336. this._delayInfo = [];
  27337. this._boundingInfo = null;
  27338. this._scene.removeGeometry(this);
  27339. this._isDisposed = true;
  27340. };
  27341. Geometry.prototype.copy = function (id) {
  27342. var vertexData = new BABYLON.VertexData();
  27343. vertexData.indices = [];
  27344. var indices = this.getIndices();
  27345. for (var index = 0; index < indices.length; index++) {
  27346. vertexData.indices.push(indices[index]);
  27347. }
  27348. var updatable = false;
  27349. var stopChecking = false;
  27350. var kind;
  27351. for (kind in this._vertexBuffers) {
  27352. // using slice() to make a copy of the array and not just reference it
  27353. var data = this.getVerticesData(kind);
  27354. if (data instanceof Float32Array) {
  27355. vertexData.set(new Float32Array(data), kind);
  27356. }
  27357. else {
  27358. vertexData.set(data.slice(0), kind);
  27359. }
  27360. if (!stopChecking) {
  27361. updatable = this.getVertexBuffer(kind).isUpdatable();
  27362. stopChecking = !updatable;
  27363. }
  27364. }
  27365. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27366. geometry.delayLoadState = this.delayLoadState;
  27367. geometry.delayLoadingFile = this.delayLoadingFile;
  27368. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27369. for (kind in this._delayInfo) {
  27370. geometry._delayInfo = geometry._delayInfo || [];
  27371. geometry._delayInfo.push(kind);
  27372. }
  27373. // Bounding info
  27374. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27375. return geometry;
  27376. };
  27377. Geometry.prototype.serialize = function () {
  27378. var serializationObject = {};
  27379. serializationObject.id = this.id;
  27380. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27381. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27382. }
  27383. return serializationObject;
  27384. };
  27385. Geometry.prototype.toNumberArray = function (origin) {
  27386. if (Array.isArray(origin)) {
  27387. return origin;
  27388. }
  27389. else {
  27390. return Array.prototype.slice.call(origin);
  27391. }
  27392. };
  27393. Geometry.prototype.serializeVerticeData = function () {
  27394. var serializationObject = this.serialize();
  27395. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27396. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27397. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27398. serializationObject.positions._updatable = true;
  27399. }
  27400. }
  27401. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27402. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27403. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27404. serializationObject.normals._updatable = true;
  27405. }
  27406. }
  27407. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27408. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27409. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27410. serializationObject.uvs._updatable = true;
  27411. }
  27412. }
  27413. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27414. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27415. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27416. serializationObject.uv2s._updatable = true;
  27417. }
  27418. }
  27419. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27420. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27421. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27422. serializationObject.uv3s._updatable = true;
  27423. }
  27424. }
  27425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27426. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27427. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27428. serializationObject.uv4s._updatable = true;
  27429. }
  27430. }
  27431. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27432. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27433. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27434. serializationObject.uv5s._updatable = true;
  27435. }
  27436. }
  27437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27438. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27439. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27440. serializationObject.uv6s._updatable = true;
  27441. }
  27442. }
  27443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27444. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27445. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27446. serializationObject.colors._updatable = true;
  27447. }
  27448. }
  27449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27450. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27451. serializationObject.matricesIndices._isExpanded = true;
  27452. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27453. serializationObject.matricesIndices._updatable = true;
  27454. }
  27455. }
  27456. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27457. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27458. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27459. serializationObject.matricesWeights._updatable = true;
  27460. }
  27461. }
  27462. serializationObject.indices = this.toNumberArray(this.getIndices());
  27463. return serializationObject;
  27464. };
  27465. // Statics
  27466. Geometry.ExtractFromMesh = function (mesh, id) {
  27467. var geometry = mesh._geometry;
  27468. if (!geometry) {
  27469. return null;
  27470. }
  27471. return geometry.copy(id);
  27472. };
  27473. /**
  27474. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27475. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27476. * Be aware Math.random() could cause collisions, but:
  27477. * "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"
  27478. */
  27479. Geometry.RandomId = function () {
  27480. return BABYLON.Tools.RandomId();
  27481. };
  27482. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27483. var scene = mesh.getScene();
  27484. // Geometry
  27485. var geometryId = parsedGeometry.geometryId;
  27486. if (geometryId) {
  27487. var geometry = scene.getGeometryByID(geometryId);
  27488. if (geometry) {
  27489. geometry.applyToMesh(mesh);
  27490. }
  27491. }
  27492. else if (parsedGeometry instanceof ArrayBuffer) {
  27493. var binaryInfo = mesh._binaryInfo;
  27494. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27495. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27496. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27497. }
  27498. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27499. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27500. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27501. }
  27502. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27503. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27504. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27505. }
  27506. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27507. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27508. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27509. }
  27510. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27511. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27512. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27513. }
  27514. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27515. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27516. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27517. }
  27518. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27519. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27520. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27521. }
  27522. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27523. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27524. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27525. }
  27526. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27527. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27528. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27529. }
  27530. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27531. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27532. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27533. }
  27534. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27535. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27536. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27537. }
  27538. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27539. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27540. mesh.setIndices(indicesData);
  27541. }
  27542. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27543. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27544. mesh.subMeshes = [];
  27545. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27546. var materialIndex = subMeshesData[(i * 5) + 0];
  27547. var verticesStart = subMeshesData[(i * 5) + 1];
  27548. var verticesCount = subMeshesData[(i * 5) + 2];
  27549. var indexStart = subMeshesData[(i * 5) + 3];
  27550. var indexCount = subMeshesData[(i * 5) + 4];
  27551. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27552. }
  27553. }
  27554. }
  27555. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27556. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27557. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27558. if (parsedGeometry.uvs) {
  27559. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27560. }
  27561. if (parsedGeometry.uvs2) {
  27562. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27563. }
  27564. if (parsedGeometry.uvs3) {
  27565. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27566. }
  27567. if (parsedGeometry.uvs4) {
  27568. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27569. }
  27570. if (parsedGeometry.uvs5) {
  27571. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27572. }
  27573. if (parsedGeometry.uvs6) {
  27574. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27575. }
  27576. if (parsedGeometry.colors) {
  27577. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27578. }
  27579. if (parsedGeometry.matricesIndices) {
  27580. if (!parsedGeometry.matricesIndices._isExpanded) {
  27581. var floatIndices = [];
  27582. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27583. var matricesIndex = parsedGeometry.matricesIndices[i];
  27584. floatIndices.push(matricesIndex & 0x000000FF);
  27585. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27586. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27587. floatIndices.push(matricesIndex >> 24);
  27588. }
  27589. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27590. }
  27591. else {
  27592. delete parsedGeometry.matricesIndices._isExpanded;
  27593. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27594. }
  27595. }
  27596. if (parsedGeometry.matricesIndicesExtra) {
  27597. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27598. var floatIndices = [];
  27599. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27600. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27601. floatIndices.push(matricesIndex & 0x000000FF);
  27602. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27603. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27604. floatIndices.push(matricesIndex >> 24);
  27605. }
  27606. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27607. }
  27608. else {
  27609. delete parsedGeometry.matricesIndices._isExpanded;
  27610. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27611. }
  27612. }
  27613. if (parsedGeometry.matricesWeights) {
  27614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27615. }
  27616. if (parsedGeometry.matricesWeightsExtra) {
  27617. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27618. }
  27619. mesh.setIndices(parsedGeometry.indices);
  27620. }
  27621. // SubMeshes
  27622. if (parsedGeometry.subMeshes) {
  27623. mesh.subMeshes = [];
  27624. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27625. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27626. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27627. }
  27628. }
  27629. // Flat shading
  27630. if (mesh._shouldGenerateFlatShading) {
  27631. mesh.convertToFlatShadedMesh();
  27632. delete mesh._shouldGenerateFlatShading;
  27633. }
  27634. // Update
  27635. mesh.computeWorldMatrix(true);
  27636. // Octree
  27637. if (scene['_selectionOctree']) {
  27638. scene['_selectionOctree'].addMesh(mesh);
  27639. }
  27640. };
  27641. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27642. if (scene.getGeometryByID(parsedVertexData.id)) {
  27643. return null; // null since geometry could be something else than a box...
  27644. }
  27645. var geometry = new Geometry(parsedVertexData.id, scene);
  27646. if (BABYLON.Tags) {
  27647. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27648. }
  27649. if (parsedVertexData.delayLoadingFile) {
  27650. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27651. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27652. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27653. geometry._delayInfo = [];
  27654. if (parsedVertexData.hasUVs) {
  27655. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27656. }
  27657. if (parsedVertexData.hasUVs2) {
  27658. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27659. }
  27660. if (parsedVertexData.hasUVs3) {
  27661. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27662. }
  27663. if (parsedVertexData.hasUVs4) {
  27664. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27665. }
  27666. if (parsedVertexData.hasUVs5) {
  27667. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27668. }
  27669. if (parsedVertexData.hasUVs6) {
  27670. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27671. }
  27672. if (parsedVertexData.hasColors) {
  27673. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27674. }
  27675. if (parsedVertexData.hasMatricesIndices) {
  27676. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27677. }
  27678. if (parsedVertexData.hasMatricesWeights) {
  27679. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27680. }
  27681. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27682. }
  27683. else {
  27684. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27685. }
  27686. scene.pushGeometry(geometry, true);
  27687. return geometry;
  27688. };
  27689. return Geometry;
  27690. }());
  27691. BABYLON.Geometry = Geometry;
  27692. /////// Primitives //////////////////////////////////////////////
  27693. (function (Geometry) {
  27694. var Primitives;
  27695. (function (Primitives) {
  27696. /// Abstract class
  27697. var _Primitive = (function (_super) {
  27698. __extends(_Primitive, _super);
  27699. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27700. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27701. _this._canBeRegenerated = _canBeRegenerated;
  27702. _this._beingRegenerated = true;
  27703. _this.regenerate();
  27704. _this._beingRegenerated = false;
  27705. return _this;
  27706. }
  27707. _Primitive.prototype.canBeRegenerated = function () {
  27708. return this._canBeRegenerated;
  27709. };
  27710. _Primitive.prototype.regenerate = function () {
  27711. if (!this._canBeRegenerated) {
  27712. return;
  27713. }
  27714. this._beingRegenerated = true;
  27715. this.setAllVerticesData(this._regenerateVertexData(), false);
  27716. this._beingRegenerated = false;
  27717. };
  27718. _Primitive.prototype.asNewGeometry = function (id) {
  27719. return _super.prototype.copy.call(this, id);
  27720. };
  27721. // overrides
  27722. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27723. if (!this._beingRegenerated) {
  27724. return;
  27725. }
  27726. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27727. };
  27728. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27729. if (!this._beingRegenerated) {
  27730. return;
  27731. }
  27732. _super.prototype.setVerticesData.call(this, kind, data, false);
  27733. };
  27734. // to override
  27735. // protected
  27736. _Primitive.prototype._regenerateVertexData = function () {
  27737. throw new Error("Abstract method");
  27738. };
  27739. _Primitive.prototype.copy = function (id) {
  27740. throw new Error("Must be overriden in sub-classes.");
  27741. };
  27742. _Primitive.prototype.serialize = function () {
  27743. var serializationObject = _super.prototype.serialize.call(this);
  27744. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27745. return serializationObject;
  27746. };
  27747. return _Primitive;
  27748. }(Geometry));
  27749. Primitives._Primitive = _Primitive;
  27750. var Ribbon = (function (_super) {
  27751. __extends(Ribbon, _super);
  27752. // Members
  27753. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27754. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27755. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27756. _this.pathArray = pathArray;
  27757. _this.closeArray = closeArray;
  27758. _this.closePath = closePath;
  27759. _this.offset = offset;
  27760. _this.side = side;
  27761. return _this;
  27762. }
  27763. Ribbon.prototype._regenerateVertexData = function () {
  27764. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27765. };
  27766. Ribbon.prototype.copy = function (id) {
  27767. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27768. };
  27769. return Ribbon;
  27770. }(_Primitive));
  27771. Primitives.Ribbon = Ribbon;
  27772. var Box = (function (_super) {
  27773. __extends(Box, _super);
  27774. // Members
  27775. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27776. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27777. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27778. _this.size = size;
  27779. _this.side = side;
  27780. return _this;
  27781. }
  27782. Box.prototype._regenerateVertexData = function () {
  27783. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27784. };
  27785. Box.prototype.copy = function (id) {
  27786. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27787. };
  27788. Box.prototype.serialize = function () {
  27789. var serializationObject = _super.prototype.serialize.call(this);
  27790. serializationObject.size = this.size;
  27791. return serializationObject;
  27792. };
  27793. Box.Parse = function (parsedBox, scene) {
  27794. if (scene.getGeometryByID(parsedBox.id)) {
  27795. return null; // null since geometry could be something else than a box...
  27796. }
  27797. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27798. if (BABYLON.Tags) {
  27799. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27800. }
  27801. scene.pushGeometry(box, true);
  27802. return box;
  27803. };
  27804. return Box;
  27805. }(_Primitive));
  27806. Primitives.Box = Box;
  27807. var Sphere = (function (_super) {
  27808. __extends(Sphere, _super);
  27809. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27810. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27811. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27812. _this.segments = segments;
  27813. _this.diameter = diameter;
  27814. _this.side = side;
  27815. return _this;
  27816. }
  27817. Sphere.prototype._regenerateVertexData = function () {
  27818. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27819. };
  27820. Sphere.prototype.copy = function (id) {
  27821. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27822. };
  27823. Sphere.prototype.serialize = function () {
  27824. var serializationObject = _super.prototype.serialize.call(this);
  27825. serializationObject.segments = this.segments;
  27826. serializationObject.diameter = this.diameter;
  27827. return serializationObject;
  27828. };
  27829. Sphere.Parse = function (parsedSphere, scene) {
  27830. if (scene.getGeometryByID(parsedSphere.id)) {
  27831. return null; // null since geometry could be something else than a sphere...
  27832. }
  27833. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27834. if (BABYLON.Tags) {
  27835. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27836. }
  27837. scene.pushGeometry(sphere, true);
  27838. return sphere;
  27839. };
  27840. return Sphere;
  27841. }(_Primitive));
  27842. Primitives.Sphere = Sphere;
  27843. var Disc = (function (_super) {
  27844. __extends(Disc, _super);
  27845. // Members
  27846. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27848. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27849. _this.radius = radius;
  27850. _this.tessellation = tessellation;
  27851. _this.side = side;
  27852. return _this;
  27853. }
  27854. Disc.prototype._regenerateVertexData = function () {
  27855. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27856. };
  27857. Disc.prototype.copy = function (id) {
  27858. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27859. };
  27860. return Disc;
  27861. }(_Primitive));
  27862. Primitives.Disc = Disc;
  27863. var Cylinder = (function (_super) {
  27864. __extends(Cylinder, _super);
  27865. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27866. if (subdivisions === void 0) { subdivisions = 1; }
  27867. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27868. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27869. _this.height = height;
  27870. _this.diameterTop = diameterTop;
  27871. _this.diameterBottom = diameterBottom;
  27872. _this.tessellation = tessellation;
  27873. _this.subdivisions = subdivisions;
  27874. _this.side = side;
  27875. return _this;
  27876. }
  27877. Cylinder.prototype._regenerateVertexData = function () {
  27878. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27879. };
  27880. Cylinder.prototype.copy = function (id) {
  27881. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27882. };
  27883. Cylinder.prototype.serialize = function () {
  27884. var serializationObject = _super.prototype.serialize.call(this);
  27885. serializationObject.height = this.height;
  27886. serializationObject.diameterTop = this.diameterTop;
  27887. serializationObject.diameterBottom = this.diameterBottom;
  27888. serializationObject.tessellation = this.tessellation;
  27889. return serializationObject;
  27890. };
  27891. Cylinder.Parse = function (parsedCylinder, scene) {
  27892. if (scene.getGeometryByID(parsedCylinder.id)) {
  27893. return null; // null since geometry could be something else than a cylinder...
  27894. }
  27895. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27896. if (BABYLON.Tags) {
  27897. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27898. }
  27899. scene.pushGeometry(cylinder, true);
  27900. return cylinder;
  27901. };
  27902. return Cylinder;
  27903. }(_Primitive));
  27904. Primitives.Cylinder = Cylinder;
  27905. var Torus = (function (_super) {
  27906. __extends(Torus, _super);
  27907. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27908. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27909. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27910. _this.diameter = diameter;
  27911. _this.thickness = thickness;
  27912. _this.tessellation = tessellation;
  27913. _this.side = side;
  27914. return _this;
  27915. }
  27916. Torus.prototype._regenerateVertexData = function () {
  27917. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27918. };
  27919. Torus.prototype.copy = function (id) {
  27920. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27921. };
  27922. Torus.prototype.serialize = function () {
  27923. var serializationObject = _super.prototype.serialize.call(this);
  27924. serializationObject.diameter = this.diameter;
  27925. serializationObject.thickness = this.thickness;
  27926. serializationObject.tessellation = this.tessellation;
  27927. return serializationObject;
  27928. };
  27929. Torus.Parse = function (parsedTorus, scene) {
  27930. if (scene.getGeometryByID(parsedTorus.id)) {
  27931. return null; // null since geometry could be something else than a torus...
  27932. }
  27933. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27934. if (BABYLON.Tags) {
  27935. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27936. }
  27937. scene.pushGeometry(torus, true);
  27938. return torus;
  27939. };
  27940. return Torus;
  27941. }(_Primitive));
  27942. Primitives.Torus = Torus;
  27943. var Ground = (function (_super) {
  27944. __extends(Ground, _super);
  27945. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27946. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27947. _this.width = width;
  27948. _this.height = height;
  27949. _this.subdivisions = subdivisions;
  27950. return _this;
  27951. }
  27952. Ground.prototype._regenerateVertexData = function () {
  27953. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27954. };
  27955. Ground.prototype.copy = function (id) {
  27956. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27957. };
  27958. Ground.prototype.serialize = function () {
  27959. var serializationObject = _super.prototype.serialize.call(this);
  27960. serializationObject.width = this.width;
  27961. serializationObject.height = this.height;
  27962. serializationObject.subdivisions = this.subdivisions;
  27963. return serializationObject;
  27964. };
  27965. Ground.Parse = function (parsedGround, scene) {
  27966. if (scene.getGeometryByID(parsedGround.id)) {
  27967. return null; // null since geometry could be something else than a ground...
  27968. }
  27969. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27970. if (BABYLON.Tags) {
  27971. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27972. }
  27973. scene.pushGeometry(ground, true);
  27974. return ground;
  27975. };
  27976. return Ground;
  27977. }(_Primitive));
  27978. Primitives.Ground = Ground;
  27979. var TiledGround = (function (_super) {
  27980. __extends(TiledGround, _super);
  27981. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27982. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27983. _this.xmin = xmin;
  27984. _this.zmin = zmin;
  27985. _this.xmax = xmax;
  27986. _this.zmax = zmax;
  27987. _this.subdivisions = subdivisions;
  27988. _this.precision = precision;
  27989. return _this;
  27990. }
  27991. TiledGround.prototype._regenerateVertexData = function () {
  27992. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27993. };
  27994. TiledGround.prototype.copy = function (id) {
  27995. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27996. };
  27997. return TiledGround;
  27998. }(_Primitive));
  27999. Primitives.TiledGround = TiledGround;
  28000. var Plane = (function (_super) {
  28001. __extends(Plane, _super);
  28002. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28005. _this.size = size;
  28006. _this.side = side;
  28007. return _this;
  28008. }
  28009. Plane.prototype._regenerateVertexData = function () {
  28010. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28011. };
  28012. Plane.prototype.copy = function (id) {
  28013. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28014. };
  28015. Plane.prototype.serialize = function () {
  28016. var serializationObject = _super.prototype.serialize.call(this);
  28017. serializationObject.size = this.size;
  28018. return serializationObject;
  28019. };
  28020. Plane.Parse = function (parsedPlane, scene) {
  28021. if (scene.getGeometryByID(parsedPlane.id)) {
  28022. return null; // null since geometry could be something else than a ground...
  28023. }
  28024. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28025. if (BABYLON.Tags) {
  28026. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28027. }
  28028. scene.pushGeometry(plane, true);
  28029. return plane;
  28030. };
  28031. return Plane;
  28032. }(_Primitive));
  28033. Primitives.Plane = Plane;
  28034. var TorusKnot = (function (_super) {
  28035. __extends(TorusKnot, _super);
  28036. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28038. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28039. _this.radius = radius;
  28040. _this.tube = tube;
  28041. _this.radialSegments = radialSegments;
  28042. _this.tubularSegments = tubularSegments;
  28043. _this.p = p;
  28044. _this.q = q;
  28045. _this.side = side;
  28046. return _this;
  28047. }
  28048. TorusKnot.prototype._regenerateVertexData = function () {
  28049. 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 });
  28050. };
  28051. TorusKnot.prototype.copy = function (id) {
  28052. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28053. };
  28054. TorusKnot.prototype.serialize = function () {
  28055. var serializationObject = _super.prototype.serialize.call(this);
  28056. serializationObject.radius = this.radius;
  28057. serializationObject.tube = this.tube;
  28058. serializationObject.radialSegments = this.radialSegments;
  28059. serializationObject.tubularSegments = this.tubularSegments;
  28060. serializationObject.p = this.p;
  28061. serializationObject.q = this.q;
  28062. return serializationObject;
  28063. };
  28064. ;
  28065. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28066. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28067. return null; // null since geometry could be something else than a ground...
  28068. }
  28069. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28070. if (BABYLON.Tags) {
  28071. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28072. }
  28073. scene.pushGeometry(torusKnot, true);
  28074. return torusKnot;
  28075. };
  28076. return TorusKnot;
  28077. }(_Primitive));
  28078. Primitives.TorusKnot = TorusKnot;
  28079. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28080. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28081. })(BABYLON || (BABYLON = {}));
  28082. //# sourceMappingURL=babylon.geometry.js.map
  28083. var BABYLON;
  28084. (function (BABYLON) {
  28085. var PostProcessManager = (function () {
  28086. function PostProcessManager(scene) {
  28087. this._vertexBuffers = {};
  28088. this._scene = scene;
  28089. }
  28090. PostProcessManager.prototype._prepareBuffers = function () {
  28091. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28092. return;
  28093. }
  28094. // VBO
  28095. var vertices = [];
  28096. vertices.push(1, 1);
  28097. vertices.push(-1, 1);
  28098. vertices.push(-1, -1);
  28099. vertices.push(1, -1);
  28100. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28101. // Indices
  28102. var indices = [];
  28103. indices.push(0);
  28104. indices.push(1);
  28105. indices.push(2);
  28106. indices.push(0);
  28107. indices.push(2);
  28108. indices.push(3);
  28109. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28110. };
  28111. // Methods
  28112. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28113. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28114. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28115. return false;
  28116. }
  28117. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28118. return true;
  28119. };
  28120. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28121. var engine = this._scene.getEngine();
  28122. for (var index = 0; index < postProcesses.length; index++) {
  28123. if (index < postProcesses.length - 1) {
  28124. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28125. }
  28126. else {
  28127. if (targetTexture) {
  28128. engine.bindFramebuffer(targetTexture);
  28129. }
  28130. else {
  28131. engine.restoreDefaultFramebuffer();
  28132. }
  28133. }
  28134. var pp = postProcesses[index];
  28135. var effect = pp.apply();
  28136. if (effect) {
  28137. pp.onBeforeRenderObservable.notifyObservers(effect);
  28138. // VBOs
  28139. this._prepareBuffers();
  28140. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28141. // Draw order
  28142. engine.draw(true, 0, 6);
  28143. pp.onAfterRenderObservable.notifyObservers(effect);
  28144. }
  28145. }
  28146. // Restore depth buffer
  28147. engine.setDepthBuffer(true);
  28148. engine.setDepthWrite(true);
  28149. };
  28150. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28151. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28152. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28153. return;
  28154. }
  28155. var engine = this._scene.getEngine();
  28156. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28157. if (index < len - 1) {
  28158. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28159. }
  28160. else {
  28161. if (targetTexture) {
  28162. engine.bindFramebuffer(targetTexture, faceIndex);
  28163. }
  28164. else {
  28165. engine.restoreDefaultFramebuffer();
  28166. }
  28167. }
  28168. if (doNotPresent) {
  28169. break;
  28170. }
  28171. var pp = postProcesses[index];
  28172. var effect = pp.apply();
  28173. if (effect) {
  28174. pp.onBeforeRenderObservable.notifyObservers(effect);
  28175. // VBOs
  28176. this._prepareBuffers();
  28177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28178. // Draw order
  28179. engine.draw(true, 0, 6);
  28180. pp.onAfterRenderObservable.notifyObservers(effect);
  28181. }
  28182. }
  28183. // Restore states
  28184. engine.setDepthBuffer(true);
  28185. engine.setDepthWrite(true);
  28186. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28187. };
  28188. PostProcessManager.prototype.dispose = function () {
  28189. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28190. if (buffer) {
  28191. buffer.dispose();
  28192. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28193. }
  28194. if (this._indexBuffer) {
  28195. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28196. this._indexBuffer = null;
  28197. }
  28198. };
  28199. return PostProcessManager;
  28200. }());
  28201. BABYLON.PostProcessManager = PostProcessManager;
  28202. })(BABYLON || (BABYLON = {}));
  28203. //# sourceMappingURL=babylon.postProcessManager.js.map
  28204. var BABYLON;
  28205. (function (BABYLON) {
  28206. var ShaderMaterial = (function (_super) {
  28207. __extends(ShaderMaterial, _super);
  28208. function ShaderMaterial(name, scene, shaderPath, options) {
  28209. var _this = _super.call(this, name, scene) || this;
  28210. _this._textures = {};
  28211. _this._textureArrays = {};
  28212. _this._floats = {};
  28213. _this._floatsArrays = {};
  28214. _this._colors3 = {};
  28215. _this._colors4 = {};
  28216. _this._vectors2 = {};
  28217. _this._vectors3 = {};
  28218. _this._vectors4 = {};
  28219. _this._matrices = {};
  28220. _this._matrices3x3 = {};
  28221. _this._matrices2x2 = {};
  28222. _this._vectors3Arrays = {};
  28223. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28224. _this._shaderPath = shaderPath;
  28225. options.needAlphaBlending = options.needAlphaBlending || false;
  28226. options.needAlphaTesting = options.needAlphaTesting || false;
  28227. options.attributes = options.attributes || ["position", "normal", "uv"];
  28228. options.uniforms = options.uniforms || ["worldViewProjection"];
  28229. options.uniformBuffers = options.uniformBuffers || [];
  28230. options.samplers = options.samplers || [];
  28231. options.defines = options.defines || [];
  28232. _this._options = options;
  28233. return _this;
  28234. }
  28235. ShaderMaterial.prototype.getClassName = function () {
  28236. return "ShaderMaterial";
  28237. };
  28238. ShaderMaterial.prototype.needAlphaBlending = function () {
  28239. return this._options.needAlphaBlending;
  28240. };
  28241. ShaderMaterial.prototype.needAlphaTesting = function () {
  28242. return this._options.needAlphaTesting;
  28243. };
  28244. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28245. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28246. this._options.uniforms.push(uniformName);
  28247. }
  28248. };
  28249. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28250. if (this._options.samplers.indexOf(name) === -1) {
  28251. this._options.samplers.push(name);
  28252. }
  28253. this._textures[name] = texture;
  28254. return this;
  28255. };
  28256. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  28257. if (this._options.samplers.indexOf(name) === -1) {
  28258. this._options.samplers.push(name);
  28259. }
  28260. this._checkUniform(name);
  28261. this._textureArrays[name] = textures;
  28262. return this;
  28263. };
  28264. ShaderMaterial.prototype.setFloat = function (name, value) {
  28265. this._checkUniform(name);
  28266. this._floats[name] = value;
  28267. return this;
  28268. };
  28269. ShaderMaterial.prototype.setFloats = function (name, value) {
  28270. this._checkUniform(name);
  28271. this._floatsArrays[name] = value;
  28272. return this;
  28273. };
  28274. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28275. this._checkUniform(name);
  28276. this._colors3[name] = value;
  28277. return this;
  28278. };
  28279. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28280. this._checkUniform(name);
  28281. this._colors4[name] = value;
  28282. return this;
  28283. };
  28284. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28285. this._checkUniform(name);
  28286. this._vectors2[name] = value;
  28287. return this;
  28288. };
  28289. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28290. this._checkUniform(name);
  28291. this._vectors3[name] = value;
  28292. return this;
  28293. };
  28294. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28295. this._checkUniform(name);
  28296. this._vectors4[name] = value;
  28297. return this;
  28298. };
  28299. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28300. this._checkUniform(name);
  28301. this._matrices[name] = value;
  28302. return this;
  28303. };
  28304. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28305. this._checkUniform(name);
  28306. this._matrices3x3[name] = value;
  28307. return this;
  28308. };
  28309. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28310. this._checkUniform(name);
  28311. this._matrices2x2[name] = value;
  28312. return this;
  28313. };
  28314. ShaderMaterial.prototype.setArray3 = function (name, value) {
  28315. this._checkUniform(name);
  28316. this._vectors3Arrays[name] = value;
  28317. return this;
  28318. };
  28319. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28320. if (!mesh) {
  28321. return true;
  28322. }
  28323. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  28324. return false;
  28325. }
  28326. return false;
  28327. };
  28328. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28329. var scene = this.getScene();
  28330. var engine = scene.getEngine();
  28331. if (!this.checkReadyOnEveryCall) {
  28332. if (this._renderId === scene.getRenderId()) {
  28333. if (this._checkCache(scene, mesh, useInstances)) {
  28334. return true;
  28335. }
  28336. }
  28337. }
  28338. // Instances
  28339. var defines = [];
  28340. var attribs = [];
  28341. var fallbacks = new BABYLON.EffectFallbacks();
  28342. if (useInstances) {
  28343. defines.push("#define INSTANCES");
  28344. }
  28345. for (var index = 0; index < this._options.defines.length; index++) {
  28346. defines.push(this._options.defines[index]);
  28347. }
  28348. for (var index = 0; index < this._options.attributes.length; index++) {
  28349. attribs.push(this._options.attributes[index]);
  28350. }
  28351. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28352. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28353. defines.push("#define VERTEXCOLOR");
  28354. }
  28355. // Bones
  28356. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28357. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28358. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28359. if (mesh.numBoneInfluencers > 4) {
  28360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28362. }
  28363. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28364. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28365. fallbacks.addCPUSkinningFallback(0, mesh);
  28366. }
  28367. else {
  28368. defines.push("#define NUM_BONE_INFLUENCERS 0");
  28369. }
  28370. // Textures
  28371. for (var name in this._textures) {
  28372. if (!this._textures[name].isReady()) {
  28373. return false;
  28374. }
  28375. }
  28376. // Alpha test
  28377. if (engine.getAlphaTesting()) {
  28378. defines.push("#define ALPHATEST");
  28379. }
  28380. var previousEffect = this._effect;
  28381. var join = defines.join("\n");
  28382. this._effect = engine.createEffect(this._shaderPath, {
  28383. attributes: attribs,
  28384. uniformsNames: this._options.uniforms,
  28385. uniformBuffersNames: this._options.uniformBuffers,
  28386. samplers: this._options.samplers,
  28387. defines: join,
  28388. fallbacks: fallbacks,
  28389. onCompiled: this.onCompiled,
  28390. onError: this.onError
  28391. }, engine);
  28392. if (!this._effect.isReady()) {
  28393. return false;
  28394. }
  28395. if (previousEffect !== this._effect) {
  28396. scene.resetCachedMaterial();
  28397. }
  28398. this._renderId = scene.getRenderId();
  28399. return true;
  28400. };
  28401. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28402. var scene = this.getScene();
  28403. if (this._options.uniforms.indexOf("world") !== -1) {
  28404. this._effect.setMatrix("world", world);
  28405. }
  28406. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28407. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28408. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28409. }
  28410. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28411. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28412. }
  28413. };
  28414. ShaderMaterial.prototype.bind = function (world, mesh) {
  28415. // Std values
  28416. this.bindOnlyWorldMatrix(world);
  28417. if (this.getScene().getCachedMaterial() !== this) {
  28418. if (this._options.uniforms.indexOf("view") !== -1) {
  28419. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28420. }
  28421. if (this._options.uniforms.indexOf("projection") !== -1) {
  28422. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28423. }
  28424. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28425. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28426. }
  28427. // Bones
  28428. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  28429. var name;
  28430. // Texture
  28431. for (name in this._textures) {
  28432. this._effect.setTexture(name, this._textures[name]);
  28433. }
  28434. // Texture arrays
  28435. for (name in this._textureArrays) {
  28436. this._effect.setTextureArray(name, this._textureArrays[name]);
  28437. }
  28438. // Float
  28439. for (name in this._floats) {
  28440. this._effect.setFloat(name, this._floats[name]);
  28441. }
  28442. // Float s
  28443. for (name in this._floatsArrays) {
  28444. this._effect.setArray(name, this._floatsArrays[name]);
  28445. }
  28446. // Color3
  28447. for (name in this._colors3) {
  28448. this._effect.setColor3(name, this._colors3[name]);
  28449. }
  28450. // Color4
  28451. for (name in this._colors4) {
  28452. var color = this._colors4[name];
  28453. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28454. }
  28455. // Vector2
  28456. for (name in this._vectors2) {
  28457. this._effect.setVector2(name, this._vectors2[name]);
  28458. }
  28459. // Vector3
  28460. for (name in this._vectors3) {
  28461. this._effect.setVector3(name, this._vectors3[name]);
  28462. }
  28463. // Vector4
  28464. for (name in this._vectors4) {
  28465. this._effect.setVector4(name, this._vectors4[name]);
  28466. }
  28467. // Matrix
  28468. for (name in this._matrices) {
  28469. this._effect.setMatrix(name, this._matrices[name]);
  28470. }
  28471. // Matrix 3x3
  28472. for (name in this._matrices3x3) {
  28473. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28474. }
  28475. // Matrix 2x2
  28476. for (name in this._matrices2x2) {
  28477. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28478. }
  28479. // Vector3Array
  28480. for (name in this._vectors3Arrays) {
  28481. this._effect.setArray3(name, this._vectors3Arrays[name]);
  28482. }
  28483. }
  28484. this._afterBind(mesh);
  28485. };
  28486. ShaderMaterial.prototype.clone = function (name) {
  28487. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28488. return newShaderMaterial;
  28489. };
  28490. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28491. if (forceDisposeTextures) {
  28492. var name;
  28493. for (name in this._textures) {
  28494. this._textures[name].dispose();
  28495. }
  28496. for (name in this._textureArrays) {
  28497. var array = this._textureArrays[name];
  28498. for (var index = 0; index < array.length; index++) {
  28499. array[index].dispose();
  28500. }
  28501. }
  28502. }
  28503. this._textures = {};
  28504. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28505. };
  28506. ShaderMaterial.prototype.serialize = function () {
  28507. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28508. serializationObject.customType = "BABYLON.ShaderMaterial";
  28509. serializationObject.options = this._options;
  28510. serializationObject.shaderPath = this._shaderPath;
  28511. var name;
  28512. // Texture
  28513. serializationObject.textures = {};
  28514. for (name in this._textures) {
  28515. serializationObject.textures[name] = this._textures[name].serialize();
  28516. }
  28517. // Texture arrays
  28518. serializationObject.textureArrays = {};
  28519. for (name in this._textureArrays) {
  28520. serializationObject.textureArrays[name] = [];
  28521. var array = this._textureArrays[name];
  28522. for (var index = 0; index < array.length; index++) {
  28523. serializationObject.textureArrays[name].push(array[index].serialize());
  28524. }
  28525. }
  28526. // Float
  28527. serializationObject.floats = {};
  28528. for (name in this._floats) {
  28529. serializationObject.floats[name] = this._floats[name];
  28530. }
  28531. // Float s
  28532. serializationObject.floatArrays = {};
  28533. for (name in this._floatsArrays) {
  28534. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28535. }
  28536. // Color3
  28537. serializationObject.colors3 = {};
  28538. for (name in this._colors3) {
  28539. serializationObject.colors3[name] = this._colors3[name].asArray();
  28540. }
  28541. // Color4
  28542. serializationObject.colors4 = {};
  28543. for (name in this._colors4) {
  28544. serializationObject.colors4[name] = this._colors4[name].asArray();
  28545. }
  28546. // Vector2
  28547. serializationObject.vectors2 = {};
  28548. for (name in this._vectors2) {
  28549. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28550. }
  28551. // Vector3
  28552. serializationObject.vectors3 = {};
  28553. for (name in this._vectors3) {
  28554. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28555. }
  28556. // Vector4
  28557. serializationObject.vectors4 = {};
  28558. for (name in this._vectors4) {
  28559. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28560. }
  28561. // Matrix
  28562. serializationObject.matrices = {};
  28563. for (name in this._matrices) {
  28564. serializationObject.matrices[name] = this._matrices[name].asArray();
  28565. }
  28566. // Matrix 3x3
  28567. serializationObject.matrices3x3 = {};
  28568. for (name in this._matrices3x3) {
  28569. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28570. }
  28571. // Matrix 2x2
  28572. serializationObject.matrices2x2 = {};
  28573. for (name in this._matrices2x2) {
  28574. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28575. }
  28576. // Vector3Array
  28577. serializationObject.vectors3Arrays = {};
  28578. for (name in this._vectors3Arrays) {
  28579. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  28580. }
  28581. return serializationObject;
  28582. };
  28583. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28584. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  28585. var name;
  28586. // Texture
  28587. for (name in source.textures) {
  28588. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28589. }
  28590. // Texture arrays
  28591. for (name in source.textureArrays) {
  28592. var array = source.textureArrays[name];
  28593. var textureArray = new Array();
  28594. for (var index = 0; index < array.length; index++) {
  28595. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  28596. }
  28597. material.setTextureArray(name, textureArray);
  28598. }
  28599. // Float
  28600. for (name in source.floats) {
  28601. material.setFloat(name, source.floats[name]);
  28602. }
  28603. // Float s
  28604. for (name in source.floatsArrays) {
  28605. material.setFloats(name, source.floatsArrays[name]);
  28606. }
  28607. // Color3
  28608. for (name in source.colors3) {
  28609. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28610. }
  28611. // Color4
  28612. for (name in source.colors4) {
  28613. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28614. }
  28615. // Vector2
  28616. for (name in source.vectors2) {
  28617. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28618. }
  28619. // Vector3
  28620. for (name in source.vectors3) {
  28621. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28622. }
  28623. // Vector4
  28624. for (name in source.vectors4) {
  28625. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28626. }
  28627. // Matrix
  28628. for (name in source.matrices) {
  28629. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28630. }
  28631. // Matrix 3x3
  28632. for (name in source.matrices3x3) {
  28633. material.setMatrix3x3(name, source.matrices3x3[name]);
  28634. }
  28635. // Matrix 2x2
  28636. for (name in source.matrices2x2) {
  28637. material.setMatrix2x2(name, source.matrices2x2[name]);
  28638. }
  28639. // Vector3Array
  28640. for (name in source.vectors3Arrays) {
  28641. material.setArray3(name, source.vectors3Arrays[name]);
  28642. }
  28643. return material;
  28644. };
  28645. return ShaderMaterial;
  28646. }(BABYLON.Material));
  28647. BABYLON.ShaderMaterial = ShaderMaterial;
  28648. })(BABYLON || (BABYLON = {}));
  28649. //# sourceMappingURL=babylon.shaderMaterial.js.map
  28650. var BABYLON;
  28651. (function (BABYLON) {
  28652. var MeshBuilder = (function () {
  28653. function MeshBuilder() {
  28654. }
  28655. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  28656. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  28657. return BABYLON.Mesh.DOUBLESIDE;
  28658. }
  28659. if (orientation === undefined || orientation === null) {
  28660. return BABYLON.Mesh.FRONTSIDE;
  28661. }
  28662. return orientation;
  28663. };
  28664. /**
  28665. * Creates a box mesh.
  28666. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  28667. * The parameter `size` sets the size (float) of each box side (default 1).
  28668. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  28669. * 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).
  28670. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  28671. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28672. * 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).
  28673. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28674. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28675. */
  28676. MeshBuilder.CreateBox = function (name, options, scene) {
  28677. var box = new BABYLON.Mesh(name, scene);
  28678. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28679. box.sideOrientation = options.sideOrientation;
  28680. var vertexData = BABYLON.VertexData.CreateBox(options);
  28681. vertexData.applyToMesh(box, options.updatable);
  28682. return box;
  28683. };
  28684. /**
  28685. * Creates a sphere mesh.
  28686. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  28687. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28688. * 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`).
  28689. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28690. * 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
  28691. * 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).
  28692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28693. * 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).
  28694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28696. */
  28697. MeshBuilder.CreateSphere = function (name, options, scene) {
  28698. var sphere = new BABYLON.Mesh(name, scene);
  28699. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28700. sphere.sideOrientation = options.sideOrientation;
  28701. var vertexData = BABYLON.VertexData.CreateSphere(options);
  28702. vertexData.applyToMesh(sphere, options.updatable);
  28703. return sphere;
  28704. };
  28705. /**
  28706. * Creates a plane polygonal mesh. By default, this is a disc.
  28707. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  28708. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28709. * 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.
  28710. * 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
  28711. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28712. * 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).
  28713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28715. */
  28716. MeshBuilder.CreateDisc = function (name, options, scene) {
  28717. var disc = new BABYLON.Mesh(name, scene);
  28718. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28719. disc.sideOrientation = options.sideOrientation;
  28720. var vertexData = BABYLON.VertexData.CreateDisc(options);
  28721. vertexData.applyToMesh(disc, options.updatable);
  28722. return disc;
  28723. };
  28724. /**
  28725. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28726. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  28727. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28728. * 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`).
  28729. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28730. * 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.
  28731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28732. * 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).
  28733. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28734. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28735. */
  28736. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  28737. var sphere = new BABYLON.Mesh(name, scene);
  28738. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28739. sphere.sideOrientation = options.sideOrientation;
  28740. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  28741. vertexData.applyToMesh(sphere, options.updatable);
  28742. return sphere;
  28743. };
  28744. ;
  28745. /**
  28746. * Creates a ribbon mesh.
  28747. * 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.
  28748. *
  28749. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28750. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28751. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28752. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28753. * 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.
  28754. * 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.
  28755. * 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
  28756. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28757. * 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).
  28758. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28759. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  28760. * 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.
  28761. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  28762. * 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
  28763. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  28764. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  28765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28766. */
  28767. MeshBuilder.CreateRibbon = function (name, options, scene) {
  28768. var pathArray = options.pathArray;
  28769. var closeArray = options.closeArray;
  28770. var closePath = options.closePath;
  28771. var offset = options.offset;
  28772. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28773. var instance = options.instance;
  28774. var updatable = options.updatable;
  28775. if (instance) {
  28776. // positionFunction : ribbon case
  28777. // only pathArray and sideOrientation parameters are taken into account for positions update
  28778. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  28779. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  28780. var positionFunction = function (positions) {
  28781. var minlg = pathArray[0].length;
  28782. var i = 0;
  28783. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  28784. for (var si = 1; si <= ns; si++) {
  28785. for (var p = 0; p < pathArray.length; p++) {
  28786. var path = pathArray[p];
  28787. var l = path.length;
  28788. minlg = (minlg < l) ? minlg : l;
  28789. var j = 0;
  28790. while (j < minlg) {
  28791. positions[i] = path[j].x;
  28792. positions[i + 1] = path[j].y;
  28793. positions[i + 2] = path[j].z;
  28794. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  28795. BABYLON.Tmp.Vector3[0].x = path[j].x;
  28796. }
  28797. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  28798. BABYLON.Tmp.Vector3[1].x = path[j].x;
  28799. }
  28800. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  28801. BABYLON.Tmp.Vector3[0].y = path[j].y;
  28802. }
  28803. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  28804. BABYLON.Tmp.Vector3[1].y = path[j].y;
  28805. }
  28806. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  28807. BABYLON.Tmp.Vector3[0].z = path[j].z;
  28808. }
  28809. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  28810. BABYLON.Tmp.Vector3[1].z = path[j].z;
  28811. }
  28812. j++;
  28813. i += 3;
  28814. }
  28815. if (instance._closePath) {
  28816. positions[i] = path[0].x;
  28817. positions[i + 1] = path[0].y;
  28818. positions[i + 2] = path[0].z;
  28819. i += 3;
  28820. }
  28821. }
  28822. }
  28823. };
  28824. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28825. positionFunction(positions);
  28826. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  28827. instance._boundingInfo.update(instance._worldMatrix);
  28828. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28829. if (options.colors) {
  28830. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28831. for (var c = 0; c < options.colors.length; c++) {
  28832. colors[c * 4] = options.colors[c].r;
  28833. colors[c * 4 + 1] = options.colors[c].g;
  28834. colors[c * 4 + 2] = options.colors[c].b;
  28835. colors[c * 4 + 3] = options.colors[c].a;
  28836. }
  28837. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  28838. }
  28839. if (options.uvs) {
  28840. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28841. for (var i = 0; i < options.uvs.length; i++) {
  28842. uvs[i * 2] = options.uvs[i].x;
  28843. uvs[i * 2 + 1] = options.uvs[i].y;
  28844. }
  28845. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  28846. }
  28847. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  28848. var indices = instance.getIndices();
  28849. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28850. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  28851. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  28852. if (instance._closePath) {
  28853. var indexFirst = 0;
  28854. var indexLast = 0;
  28855. for (var p = 0; p < pathArray.length; p++) {
  28856. indexFirst = instance._idx[p] * 3;
  28857. if (p + 1 < pathArray.length) {
  28858. indexLast = (instance._idx[p + 1] - 1) * 3;
  28859. }
  28860. else {
  28861. indexLast = normals.length - 3;
  28862. }
  28863. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28864. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28865. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28866. normals[indexLast] = normals[indexFirst];
  28867. normals[indexLast + 1] = normals[indexFirst + 1];
  28868. normals[indexLast + 2] = normals[indexFirst + 2];
  28869. }
  28870. }
  28871. if (!(instance.areNormalsFrozen)) {
  28872. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28873. }
  28874. }
  28875. return instance;
  28876. }
  28877. else {
  28878. var ribbon = new BABYLON.Mesh(name, scene);
  28879. ribbon.sideOrientation = sideOrientation;
  28880. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  28881. if (closePath) {
  28882. ribbon._idx = vertexData._idx;
  28883. }
  28884. ribbon._closePath = closePath;
  28885. ribbon._closeArray = closeArray;
  28886. vertexData.applyToMesh(ribbon, updatable);
  28887. return ribbon;
  28888. }
  28889. };
  28890. /**
  28891. * Creates a cylinder or a cone mesh.
  28892. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  28893. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28894. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28895. * 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.
  28896. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28897. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28898. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  28899. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  28900. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  28901. * 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).
  28902. * 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
  28903. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  28904. * 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
  28905. * 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.
  28906. * If `enclose` is false, a ring surface is one element.
  28907. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  28908. * 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
  28909. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28910. * 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).
  28911. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28913. */
  28914. MeshBuilder.CreateCylinder = function (name, options, scene) {
  28915. var cylinder = new BABYLON.Mesh(name, scene);
  28916. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28917. cylinder.sideOrientation = options.sideOrientation;
  28918. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  28919. vertexData.applyToMesh(cylinder, options.updatable);
  28920. return cylinder;
  28921. };
  28922. /**
  28923. * Creates a torus mesh.
  28924. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  28925. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28926. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28927. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28928. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28929. * 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).
  28930. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28932. */
  28933. MeshBuilder.CreateTorus = function (name, options, scene) {
  28934. var torus = new BABYLON.Mesh(name, scene);
  28935. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28936. torus.sideOrientation = options.sideOrientation;
  28937. var vertexData = BABYLON.VertexData.CreateTorus(options);
  28938. vertexData.applyToMesh(torus, options.updatable);
  28939. return torus;
  28940. };
  28941. /**
  28942. * Creates a torus knot mesh.
  28943. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  28944. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28945. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28946. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28947. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28948. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28949. * 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).
  28950. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28952. */
  28953. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  28954. var torusKnot = new BABYLON.Mesh(name, scene);
  28955. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28956. torusKnot.sideOrientation = options.sideOrientation;
  28957. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  28958. vertexData.applyToMesh(torusKnot, options.updatable);
  28959. return torusKnot;
  28960. };
  28961. /**
  28962. * Creates a line system mesh.
  28963. * A line system is a pool of many lines gathered in a single mesh.
  28964. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  28965. * 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.
  28966. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  28967. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  28968. * 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
  28969. * 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
  28970. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  28971. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28972. */
  28973. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  28974. var instance = options.instance;
  28975. var lines = options.lines;
  28976. if (instance) {
  28977. var positionFunction = function (positions) {
  28978. var i = 0;
  28979. for (var l = 0; l < lines.length; l++) {
  28980. var points = lines[l];
  28981. for (var p = 0; p < points.length; p++) {
  28982. positions[i] = points[p].x;
  28983. positions[i + 1] = points[p].y;
  28984. positions[i + 2] = points[p].z;
  28985. i += 3;
  28986. }
  28987. }
  28988. };
  28989. instance.updateMeshPositions(positionFunction, false);
  28990. return instance;
  28991. }
  28992. // line system creation
  28993. var lineSystem = new BABYLON.LinesMesh(name, scene);
  28994. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  28995. vertexData.applyToMesh(lineSystem, options.updatable);
  28996. return lineSystem;
  28997. };
  28998. /**
  28999. * Creates a line mesh.
  29000. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  29001. * 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.
  29002. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29003. * The parameter `points` is an array successive Vector3.
  29004. * 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
  29005. * When updating an instance, remember that only point positions can change, not the number of points.
  29006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29007. */
  29008. MeshBuilder.CreateLines = function (name, options, scene) {
  29009. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  29010. return lines;
  29011. };
  29012. /**
  29013. * Creates a dashed line mesh.
  29014. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  29015. * 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.
  29016. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29017. * The parameter `points` is an array successive Vector3.
  29018. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29019. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29020. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29021. * 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
  29022. * When updating an instance, remember that only point positions can change, not the number of points.
  29023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29024. */
  29025. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  29026. var points = options.points;
  29027. var instance = options.instance;
  29028. var gapSize = options.gapSize;
  29029. var dashNb = options.dashNb;
  29030. var dashSize = options.dashSize;
  29031. if (instance) {
  29032. var positionFunction = function (positions) {
  29033. var curvect = BABYLON.Vector3.Zero();
  29034. var nbSeg = positions.length / 6;
  29035. var lg = 0;
  29036. var nb = 0;
  29037. var shft = 0;
  29038. var dashshft = 0;
  29039. var curshft = 0;
  29040. var p = 0;
  29041. var i = 0;
  29042. var j = 0;
  29043. for (i = 0; i < points.length - 1; i++) {
  29044. points[i + 1].subtractToRef(points[i], curvect);
  29045. lg += curvect.length();
  29046. }
  29047. shft = lg / nbSeg;
  29048. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  29049. for (i = 0; i < points.length - 1; i++) {
  29050. points[i + 1].subtractToRef(points[i], curvect);
  29051. nb = Math.floor(curvect.length() / shft);
  29052. curvect.normalize();
  29053. j = 0;
  29054. while (j < nb && p < positions.length) {
  29055. curshft = shft * j;
  29056. positions[p] = points[i].x + curshft * curvect.x;
  29057. positions[p + 1] = points[i].y + curshft * curvect.y;
  29058. positions[p + 2] = points[i].z + curshft * curvect.z;
  29059. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  29060. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  29061. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  29062. p += 6;
  29063. j++;
  29064. }
  29065. }
  29066. while (p < positions.length) {
  29067. positions[p] = points[i].x;
  29068. positions[p + 1] = points[i].y;
  29069. positions[p + 2] = points[i].z;
  29070. p += 3;
  29071. }
  29072. };
  29073. instance.updateMeshPositions(positionFunction, false);
  29074. return instance;
  29075. }
  29076. // dashed lines creation
  29077. var dashedLines = new BABYLON.LinesMesh(name, scene);
  29078. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  29079. vertexData.applyToMesh(dashedLines, options.updatable);
  29080. dashedLines.dashSize = dashSize;
  29081. dashedLines.gapSize = gapSize;
  29082. return dashedLines;
  29083. };
  29084. /**
  29085. * Creates an extruded shape mesh.
  29086. * 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.
  29087. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  29088. *
  29089. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29090. * 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
  29091. * extruded along the Z axis.
  29092. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29093. * 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.
  29094. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29095. * 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
  29096. * 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
  29097. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29098. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29099. * 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).
  29100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29101. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29103. */
  29104. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  29105. var path = options.path;
  29106. var shape = options.shape;
  29107. var scale = options.scale || 1;
  29108. var rotation = options.rotation || 0;
  29109. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  29110. var updatable = options.updatable;
  29111. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29112. var instance = options.instance;
  29113. var invertUV = options.invertUV || false;
  29114. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  29115. };
  29116. /**
  29117. * Creates an custom extruded shape mesh.
  29118. * 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.
  29119. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  29120. *
  29121. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29122. * 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
  29123. * extruded along the Z axis.
  29124. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29125. * 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
  29126. * and the distance of this point from the begining of the path :
  29127. * ```javascript
  29128. * var rotationFunction = function(i, distance) {
  29129. * // do things
  29130. * return rotationValue; }
  29131. * ```
  29132. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29133. * 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
  29134. * and the distance of this point from the begining of the path :
  29135. * ```javascript
  29136. * var scaleFunction = function(i, distance) {
  29137. * // do things
  29138. * return scaleValue;}
  29139. * ```
  29140. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29141. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29142. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29143. * 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
  29144. * 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
  29145. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29147. * 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).
  29148. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29149. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29151. */
  29152. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  29153. var path = options.path;
  29154. var shape = options.shape;
  29155. var scaleFunction = options.scaleFunction || (function () { return 1; });
  29156. var rotationFunction = options.rotationFunction || (function () { return 0; });
  29157. var ribbonCloseArray = options.ribbonCloseArray || false;
  29158. var ribbonClosePath = options.ribbonClosePath || false;
  29159. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  29160. var updatable = options.updatable;
  29161. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29162. var instance = options.instance;
  29163. var invertUV = options.invertUV || false;
  29164. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  29165. };
  29166. /**
  29167. * Creates lathe mesh.
  29168. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29169. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  29170. *
  29171. * 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
  29172. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29173. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29174. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29175. * 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.
  29176. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  29177. * 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
  29178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29179. * 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).
  29180. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29181. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29183. */
  29184. MeshBuilder.CreateLathe = function (name, options, scene) {
  29185. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  29186. var closed = (options.closed === undefined) ? true : options.closed;
  29187. var shape = options.shape;
  29188. var radius = options.radius || 1;
  29189. var tessellation = options.tessellation || 64;
  29190. var updatable = options.updatable;
  29191. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29192. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29193. var pi2 = Math.PI * 2;
  29194. var paths = new Array();
  29195. var invertUV = options.invertUV || false;
  29196. var i = 0;
  29197. var p = 0;
  29198. var step = pi2 / tessellation * arc;
  29199. var rotated;
  29200. var path = new Array();
  29201. ;
  29202. for (i = 0; i <= tessellation; i++) {
  29203. var path = [];
  29204. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  29205. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  29206. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  29207. }
  29208. for (p = 0; p < shape.length; p++) {
  29209. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  29210. path.push(rotated);
  29211. }
  29212. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  29213. 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));
  29214. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  29215. }
  29216. paths.push(path);
  29217. }
  29218. // lathe ribbon
  29219. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29220. return lathe;
  29221. };
  29222. /**
  29223. * Creates a plane mesh.
  29224. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29225. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29226. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  29227. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  29228. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29229. * 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).
  29230. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29232. */
  29233. MeshBuilder.CreatePlane = function (name, options, scene) {
  29234. var plane = new BABYLON.Mesh(name, scene);
  29235. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29236. plane.sideOrientation = options.sideOrientation;
  29237. var vertexData = BABYLON.VertexData.CreatePlane(options);
  29238. vertexData.applyToMesh(plane, options.updatable);
  29239. if (options.sourcePlane) {
  29240. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  29241. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  29242. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  29243. plane.rotate(vectorProduct, product);
  29244. }
  29245. return plane;
  29246. };
  29247. /**
  29248. * Creates a ground mesh.
  29249. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29250. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29251. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29253. */
  29254. MeshBuilder.CreateGround = function (name, options, scene) {
  29255. var ground = new BABYLON.GroundMesh(name, scene);
  29256. ground._setReady(false);
  29257. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29258. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29259. ground._width = options.width || 1;
  29260. ground._height = options.height || 1;
  29261. ground._maxX = ground._width / 2;
  29262. ground._maxZ = ground._height / 2;
  29263. ground._minX = -ground._maxX;
  29264. ground._minZ = -ground._maxZ;
  29265. var vertexData = BABYLON.VertexData.CreateGround(options);
  29266. vertexData.applyToMesh(ground, options.updatable);
  29267. ground._setReady(true);
  29268. return ground;
  29269. };
  29270. /**
  29271. * Creates a tiled ground mesh.
  29272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  29273. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29274. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29275. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29276. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29277. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29278. * numbers of subdivisions on the ground width and height of each tile.
  29279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29280. */
  29281. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  29282. var tiledGround = new BABYLON.Mesh(name, scene);
  29283. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  29284. vertexData.applyToMesh(tiledGround, options.updatable);
  29285. return tiledGround;
  29286. };
  29287. /**
  29288. * Creates a ground mesh from a height map.
  29289. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29290. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  29291. * The parameter `url` sets the URL of the height map image resource.
  29292. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29293. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29294. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29295. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29296. * 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.
  29297. * 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).
  29298. * This function is passed the newly built mesh :
  29299. * ```javascript
  29300. * function(mesh) { // do things
  29301. * return; }
  29302. * ```
  29303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29304. */
  29305. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  29306. var width = options.width || 10.0;
  29307. var height = options.height || 10.0;
  29308. var subdivisions = options.subdivisions || 1 | 0;
  29309. var minHeight = options.minHeight || 0.0;
  29310. var maxHeight = options.maxHeight || 10.0;
  29311. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29312. var updatable = options.updatable;
  29313. var onReady = options.onReady;
  29314. var ground = new BABYLON.GroundMesh(name, scene);
  29315. ground._subdivisionsX = subdivisions;
  29316. ground._subdivisionsY = subdivisions;
  29317. ground._width = width;
  29318. ground._height = height;
  29319. ground._maxX = ground._width / 2.0;
  29320. ground._maxZ = ground._height / 2.0;
  29321. ground._minX = -ground._maxX;
  29322. ground._minZ = -ground._maxZ;
  29323. ground._setReady(false);
  29324. var onload = function (img) {
  29325. // Getting height map data
  29326. var canvas = document.createElement("canvas");
  29327. var context = canvas.getContext("2d");
  29328. var bufferWidth = img.width;
  29329. var bufferHeight = img.height;
  29330. canvas.width = bufferWidth;
  29331. canvas.height = bufferHeight;
  29332. context.drawImage(img, 0, 0);
  29333. // Create VertexData from map data
  29334. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29335. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  29336. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  29337. width: width, height: height,
  29338. subdivisions: subdivisions,
  29339. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  29340. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  29341. });
  29342. vertexData.applyToMesh(ground, updatable);
  29343. ground._setReady(true);
  29344. //execute ready callback, if set
  29345. if (onReady) {
  29346. onReady(ground);
  29347. }
  29348. };
  29349. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29350. return ground;
  29351. };
  29352. /**
  29353. * Creates a polygon mesh.
  29354. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29355. * 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.
  29356. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29358. * 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).
  29359. * Remember you can only change the shape positions, not their number when updating a polygon.
  29360. */
  29361. MeshBuilder.CreatePolygon = function (name, options, scene) {
  29362. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29363. var shape = options.shape;
  29364. var holes = options.holes || [];
  29365. var depth = options.depth || 0;
  29366. var contours = [];
  29367. var hole = [];
  29368. for (var i = 0; i < shape.length; i++) {
  29369. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  29370. }
  29371. var epsilon = 0.00000001;
  29372. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  29373. contours.pop();
  29374. }
  29375. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  29376. for (var hNb = 0; hNb < holes.length; hNb++) {
  29377. hole = [];
  29378. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  29379. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  29380. }
  29381. polygonTriangulation.addHole(hole);
  29382. }
  29383. var polygon = polygonTriangulation.build(options.updatable, depth);
  29384. polygon.sideOrientation = options.sideOrientation;
  29385. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  29386. vertexData.applyToMesh(polygon, options.updatable);
  29387. return polygon;
  29388. };
  29389. ;
  29390. /**
  29391. * Creates an extruded polygon mesh, with depth in the Y direction.
  29392. * 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).
  29393. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  29394. */
  29395. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  29396. return MeshBuilder.CreatePolygon(name, options, scene);
  29397. };
  29398. ;
  29399. /**
  29400. * Creates a tube mesh.
  29401. * 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.
  29402. *
  29403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  29404. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29405. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29406. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29407. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29408. * 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.
  29409. * It must return a radius value (positive float) :
  29410. * ```javascript
  29411. * var radiusFunction = function(i, distance) {
  29412. * // do things
  29413. * return radius; }
  29414. * ```
  29415. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  29416. * 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
  29417. * 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
  29418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29419. * 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).
  29420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29421. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29422. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29423. */
  29424. MeshBuilder.CreateTube = function (name, options, scene) {
  29425. var path = options.path;
  29426. var radius = options.radius || 1.0;
  29427. var tessellation = options.tessellation || 64 | 0;
  29428. var radiusFunction = options.radiusFunction;
  29429. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29430. var invertUV = options.invertUV || false;
  29431. var updatable = options.updatable;
  29432. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29433. var instance = options.instance;
  29434. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  29435. // tube geometry
  29436. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  29437. var tangents = path3D.getTangents();
  29438. var normals = path3D.getNormals();
  29439. var distances = path3D.getDistances();
  29440. var pi2 = Math.PI * 2;
  29441. var step = pi2 / tessellation * arc;
  29442. var returnRadius = function () { return radius; };
  29443. var radiusFunctionFinal = radiusFunction || returnRadius;
  29444. var circlePath;
  29445. var rad;
  29446. var normal;
  29447. var rotated;
  29448. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29449. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29450. for (var i = 0; i < path.length; i++) {
  29451. rad = radiusFunctionFinal(i, distances[i]); // current radius
  29452. circlePath = Array(); // current circle array
  29453. normal = normals[i]; // current normal
  29454. for (var t = 0; t < tessellation; t++) {
  29455. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  29456. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  29457. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  29458. rotated.scaleInPlace(rad).addInPlace(path[i]);
  29459. circlePath[t] = rotated;
  29460. }
  29461. circlePaths[index] = circlePath;
  29462. index++;
  29463. }
  29464. // cap
  29465. var capPath = function (nbPoints, pathIndex) {
  29466. var pointCap = Array();
  29467. for (var i = 0; i < nbPoints; i++) {
  29468. pointCap.push(path[pathIndex]);
  29469. }
  29470. return pointCap;
  29471. };
  29472. switch (cap) {
  29473. case BABYLON.Mesh.NO_CAP:
  29474. break;
  29475. case BABYLON.Mesh.CAP_START:
  29476. circlePaths[0] = capPath(tessellation, 0);
  29477. circlePaths[1] = circlePaths[2].slice(0);
  29478. break;
  29479. case BABYLON.Mesh.CAP_END:
  29480. circlePaths[index] = circlePaths[index - 1].slice(0);
  29481. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29482. break;
  29483. case BABYLON.Mesh.CAP_ALL:
  29484. circlePaths[0] = capPath(tessellation, 0);
  29485. circlePaths[1] = circlePaths[2].slice(0);
  29486. circlePaths[index] = circlePaths[index - 1].slice(0);
  29487. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29488. break;
  29489. default:
  29490. break;
  29491. }
  29492. return circlePaths;
  29493. };
  29494. var path3D;
  29495. var pathArray;
  29496. if (instance) {
  29497. var arc = options.arc || instance.arc;
  29498. path3D = (instance.path3D).update(path);
  29499. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  29500. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  29501. instance.path3D = path3D;
  29502. instance.pathArray = pathArray;
  29503. instance.arc = arc;
  29504. return instance;
  29505. }
  29506. // tube creation
  29507. path3D = new BABYLON.Path3D(path);
  29508. var newPathArray = new Array();
  29509. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29510. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  29511. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29512. tube.pathArray = pathArray;
  29513. tube.path3D = path3D;
  29514. tube.tessellation = tessellation;
  29515. tube.cap = cap;
  29516. tube.arc = options.arc;
  29517. return tube;
  29518. };
  29519. /**
  29520. * Creates a polyhedron mesh.
  29521. *
  29522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  29523. * 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
  29524. * to choose the wanted type.
  29525. * The parameter `size` (positive float, default 1) sets the polygon size.
  29526. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29527. * 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`.
  29528. * 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
  29529. * 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)`).
  29530. * 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
  29531. * 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.
  29532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29533. * 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).
  29534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29536. */
  29537. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  29538. var polyhedron = new BABYLON.Mesh(name, scene);
  29539. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29540. polyhedron.sideOrientation = options.sideOrientation;
  29541. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  29542. vertexData.applyToMesh(polyhedron, options.updatable);
  29543. return polyhedron;
  29544. };
  29545. /**
  29546. * Creates a decal mesh.
  29547. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  29548. * 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.
  29549. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29550. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29551. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29552. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29553. */
  29554. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  29555. var indices = sourceMesh.getIndices();
  29556. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29557. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29558. var position = options.position || BABYLON.Vector3.Zero();
  29559. var normal = options.normal || BABYLON.Vector3.Up();
  29560. var size = options.size || BABYLON.Vector3.One();
  29561. var angle = options.angle || 0;
  29562. // Getting correct rotation
  29563. if (!normal) {
  29564. var target = new BABYLON.Vector3(0, 0, 1);
  29565. var camera = sourceMesh.getScene().activeCamera;
  29566. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  29567. normal = camera.globalPosition.subtract(cameraWorldTarget);
  29568. }
  29569. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  29570. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  29571. var pitch = Math.atan2(normal.y, len);
  29572. // Matrix
  29573. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  29574. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  29575. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  29576. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  29577. var vertexData = new BABYLON.VertexData();
  29578. vertexData.indices = [];
  29579. vertexData.positions = [];
  29580. vertexData.normals = [];
  29581. vertexData.uvs = [];
  29582. var currentVertexDataIndex = 0;
  29583. var extractDecalVector3 = function (indexId) {
  29584. var vertexId = indices[indexId];
  29585. var result = new BABYLON.PositionNormalVertex();
  29586. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  29587. // Send vector to decal local world
  29588. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  29589. // Get normal
  29590. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  29591. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  29592. return result;
  29593. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  29594. var clip = function (vertices, axis) {
  29595. if (vertices.length === 0) {
  29596. return vertices;
  29597. }
  29598. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  29599. var clipVertices = function (v0, v1) {
  29600. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  29601. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  29602. };
  29603. var result = new Array();
  29604. for (var index = 0; index < vertices.length; index += 3) {
  29605. var v1Out;
  29606. var v2Out;
  29607. var v3Out;
  29608. var total = 0;
  29609. var nV1, nV2, nV3, nV4;
  29610. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  29611. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  29612. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  29613. v1Out = d1 > 0;
  29614. v2Out = d2 > 0;
  29615. v3Out = d3 > 0;
  29616. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  29617. switch (total) {
  29618. case 0:
  29619. result.push(vertices[index]);
  29620. result.push(vertices[index + 1]);
  29621. result.push(vertices[index + 2]);
  29622. break;
  29623. case 1:
  29624. if (v1Out) {
  29625. nV1 = vertices[index + 1];
  29626. nV2 = vertices[index + 2];
  29627. nV3 = clipVertices(vertices[index], nV1);
  29628. nV4 = clipVertices(vertices[index], nV2);
  29629. }
  29630. if (v2Out) {
  29631. nV1 = vertices[index];
  29632. nV2 = vertices[index + 2];
  29633. nV3 = clipVertices(vertices[index + 1], nV1);
  29634. nV4 = clipVertices(vertices[index + 1], nV2);
  29635. result.push(nV3);
  29636. result.push(nV2.clone());
  29637. result.push(nV1.clone());
  29638. result.push(nV2.clone());
  29639. result.push(nV3.clone());
  29640. result.push(nV4);
  29641. break;
  29642. }
  29643. if (v3Out) {
  29644. nV1 = vertices[index];
  29645. nV2 = vertices[index + 1];
  29646. nV3 = clipVertices(vertices[index + 2], nV1);
  29647. nV4 = clipVertices(vertices[index + 2], nV2);
  29648. }
  29649. result.push(nV1.clone());
  29650. result.push(nV2.clone());
  29651. result.push(nV3);
  29652. result.push(nV4);
  29653. result.push(nV3.clone());
  29654. result.push(nV2.clone());
  29655. break;
  29656. case 2:
  29657. if (!v1Out) {
  29658. nV1 = vertices[index].clone();
  29659. nV2 = clipVertices(nV1, vertices[index + 1]);
  29660. nV3 = clipVertices(nV1, vertices[index + 2]);
  29661. result.push(nV1);
  29662. result.push(nV2);
  29663. result.push(nV3);
  29664. }
  29665. if (!v2Out) {
  29666. nV1 = vertices[index + 1].clone();
  29667. nV2 = clipVertices(nV1, vertices[index + 2]);
  29668. nV3 = clipVertices(nV1, vertices[index]);
  29669. result.push(nV1);
  29670. result.push(nV2);
  29671. result.push(nV3);
  29672. }
  29673. if (!v3Out) {
  29674. nV1 = vertices[index + 2].clone();
  29675. nV2 = clipVertices(nV1, vertices[index]);
  29676. nV3 = clipVertices(nV1, vertices[index + 1]);
  29677. result.push(nV1);
  29678. result.push(nV2);
  29679. result.push(nV3);
  29680. }
  29681. break;
  29682. case 3:
  29683. break;
  29684. }
  29685. }
  29686. return result;
  29687. };
  29688. for (var index = 0; index < indices.length; index += 3) {
  29689. var faceVertices = new Array();
  29690. faceVertices.push(extractDecalVector3(index));
  29691. faceVertices.push(extractDecalVector3(index + 1));
  29692. faceVertices.push(extractDecalVector3(index + 2));
  29693. // Clip
  29694. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  29695. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  29696. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  29697. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  29698. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  29699. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  29700. if (faceVertices.length === 0) {
  29701. continue;
  29702. }
  29703. // Add UVs and get back to world
  29704. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  29705. var vertex = faceVertices[vIndex];
  29706. //TODO check for Int32Array | Uint32Array | Uint16Array
  29707. vertexData.indices.push(currentVertexDataIndex);
  29708. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  29709. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  29710. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  29711. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  29712. currentVertexDataIndex++;
  29713. }
  29714. }
  29715. // Return mesh
  29716. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  29717. vertexData.applyToMesh(decal);
  29718. decal.position = position.clone();
  29719. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  29720. return decal;
  29721. };
  29722. // Privates
  29723. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  29724. // extrusion geometry
  29725. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  29726. var tangents = path3D.getTangents();
  29727. var normals = path3D.getNormals();
  29728. var binormals = path3D.getBinormals();
  29729. var distances = path3D.getDistances();
  29730. var angle = 0;
  29731. var returnScale = function () { return scale; };
  29732. var returnRotation = function () { return rotation; };
  29733. var rotate = custom ? rotateFunction : returnRotation;
  29734. var scl = custom ? scaleFunction : returnScale;
  29735. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29736. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29737. for (var i = 0; i < curve.length; i++) {
  29738. var shapePath = new Array();
  29739. var angleStep = rotate(i, distances[i]);
  29740. var scaleRatio = scl(i, distances[i]);
  29741. for (var p = 0; p < shape.length; p++) {
  29742. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  29743. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  29744. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  29745. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  29746. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  29747. shapePath[p] = rotated;
  29748. }
  29749. shapePaths[index] = shapePath;
  29750. angle += angleStep;
  29751. index++;
  29752. }
  29753. // cap
  29754. var capPath = function (shapePath) {
  29755. var pointCap = Array();
  29756. var barycenter = BABYLON.Vector3.Zero();
  29757. var i;
  29758. for (i = 0; i < shapePath.length; i++) {
  29759. barycenter.addInPlace(shapePath[i]);
  29760. }
  29761. barycenter.scaleInPlace(1.0 / shapePath.length);
  29762. for (i = 0; i < shapePath.length; i++) {
  29763. pointCap.push(barycenter);
  29764. }
  29765. return pointCap;
  29766. };
  29767. switch (cap) {
  29768. case BABYLON.Mesh.NO_CAP:
  29769. break;
  29770. case BABYLON.Mesh.CAP_START:
  29771. shapePaths[0] = capPath(shapePaths[2]);
  29772. shapePaths[1] = shapePaths[2];
  29773. break;
  29774. case BABYLON.Mesh.CAP_END:
  29775. shapePaths[index] = shapePaths[index - 1];
  29776. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29777. break;
  29778. case BABYLON.Mesh.CAP_ALL:
  29779. shapePaths[0] = capPath(shapePaths[2]);
  29780. shapePaths[1] = shapePaths[2];
  29781. shapePaths[index] = shapePaths[index - 1];
  29782. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29783. break;
  29784. default:
  29785. break;
  29786. }
  29787. return shapePaths;
  29788. };
  29789. var path3D;
  29790. var pathArray;
  29791. if (instance) {
  29792. path3D = (instance.path3D).update(curve);
  29793. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  29794. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  29795. return instance;
  29796. }
  29797. // extruded shape creation
  29798. path3D = new BABYLON.Path3D(curve);
  29799. var newShapePaths = new Array();
  29800. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29801. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  29802. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  29803. extrudedGeneric.pathArray = pathArray;
  29804. extrudedGeneric.path3D = path3D;
  29805. extrudedGeneric.cap = cap;
  29806. return extrudedGeneric;
  29807. };
  29808. return MeshBuilder;
  29809. }());
  29810. BABYLON.MeshBuilder = MeshBuilder;
  29811. })(BABYLON || (BABYLON = {}));
  29812. //# sourceMappingURL=babylon.meshBuilder.js.map
  29813. var BABYLON;
  29814. (function (BABYLON) {
  29815. var AnimationRange = (function () {
  29816. function AnimationRange(name, from, to) {
  29817. this.name = name;
  29818. this.from = from;
  29819. this.to = to;
  29820. }
  29821. AnimationRange.prototype.clone = function () {
  29822. return new AnimationRange(this.name, this.from, this.to);
  29823. };
  29824. return AnimationRange;
  29825. }());
  29826. BABYLON.AnimationRange = AnimationRange;
  29827. /**
  29828. * Composed of a frame, and an action function
  29829. */
  29830. var AnimationEvent = (function () {
  29831. function AnimationEvent(frame, action, onlyOnce) {
  29832. this.frame = frame;
  29833. this.action = action;
  29834. this.onlyOnce = onlyOnce;
  29835. this.isDone = false;
  29836. }
  29837. return AnimationEvent;
  29838. }());
  29839. BABYLON.AnimationEvent = AnimationEvent;
  29840. var PathCursor = (function () {
  29841. function PathCursor(path) {
  29842. this.path = path;
  29843. this._onchange = new Array();
  29844. this.value = 0;
  29845. this.animations = new Array();
  29846. }
  29847. PathCursor.prototype.getPoint = function () {
  29848. var point = this.path.getPointAtLengthPosition(this.value);
  29849. return new BABYLON.Vector3(point.x, 0, point.y);
  29850. };
  29851. PathCursor.prototype.moveAhead = function (step) {
  29852. if (step === void 0) { step = 0.002; }
  29853. this.move(step);
  29854. return this;
  29855. };
  29856. PathCursor.prototype.moveBack = function (step) {
  29857. if (step === void 0) { step = 0.002; }
  29858. this.move(-step);
  29859. return this;
  29860. };
  29861. PathCursor.prototype.move = function (step) {
  29862. if (Math.abs(step) > 1) {
  29863. throw "step size should be less than 1.";
  29864. }
  29865. this.value += step;
  29866. this.ensureLimits();
  29867. this.raiseOnChange();
  29868. return this;
  29869. };
  29870. PathCursor.prototype.ensureLimits = function () {
  29871. while (this.value > 1) {
  29872. this.value -= 1;
  29873. }
  29874. while (this.value < 0) {
  29875. this.value += 1;
  29876. }
  29877. return this;
  29878. };
  29879. // used by animation engine
  29880. PathCursor.prototype.markAsDirty = function (propertyName) {
  29881. this.ensureLimits();
  29882. this.raiseOnChange();
  29883. return this;
  29884. };
  29885. PathCursor.prototype.raiseOnChange = function () {
  29886. var _this = this;
  29887. this._onchange.forEach(function (f) { return f(_this); });
  29888. return this;
  29889. };
  29890. PathCursor.prototype.onchange = function (f) {
  29891. this._onchange.push(f);
  29892. return this;
  29893. };
  29894. return PathCursor;
  29895. }());
  29896. BABYLON.PathCursor = PathCursor;
  29897. var Animation = (function () {
  29898. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29899. this.name = name;
  29900. this.targetProperty = targetProperty;
  29901. this.framePerSecond = framePerSecond;
  29902. this.dataType = dataType;
  29903. this.loopMode = loopMode;
  29904. this.enableBlending = enableBlending;
  29905. this._offsetsCache = {};
  29906. this._highLimitsCache = {};
  29907. this._stopped = false;
  29908. this._blendingFactor = 0;
  29909. // The set of event that will be linked to this animation
  29910. this._events = new Array();
  29911. this.allowMatricesInterpolation = false;
  29912. this.blendingSpeed = 0.01;
  29913. this._ranges = {};
  29914. this.targetPropertyPath = targetProperty.split(".");
  29915. this.dataType = dataType;
  29916. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29917. }
  29918. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29919. var dataType = undefined;
  29920. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29921. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29922. }
  29923. else if (from instanceof BABYLON.Quaternion) {
  29924. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29925. }
  29926. else if (from instanceof BABYLON.Vector3) {
  29927. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29928. }
  29929. else if (from instanceof BABYLON.Vector2) {
  29930. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29931. }
  29932. else if (from instanceof BABYLON.Color3) {
  29933. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29934. }
  29935. else if (from instanceof BABYLON.Size) {
  29936. dataType = Animation.ANIMATIONTYPE_SIZE;
  29937. }
  29938. if (dataType == undefined) {
  29939. return null;
  29940. }
  29941. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29942. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29943. animation.setKeys(keys);
  29944. if (easingFunction !== undefined) {
  29945. animation.setEasingFunction(easingFunction);
  29946. }
  29947. return animation;
  29948. };
  29949. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29950. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29951. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29952. };
  29953. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29954. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29955. node.animations.push(animation);
  29956. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29957. };
  29958. // Methods
  29959. /**
  29960. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29961. */
  29962. Animation.prototype.toString = function (fullDetails) {
  29963. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29964. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29965. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29966. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29967. if (fullDetails) {
  29968. ret += ", Ranges: {";
  29969. var first = true;
  29970. for (var name in this._ranges) {
  29971. if (first) {
  29972. ret += ", ";
  29973. first = false;
  29974. }
  29975. ret += name;
  29976. }
  29977. ret += "}";
  29978. }
  29979. return ret;
  29980. };
  29981. /**
  29982. * Add an event to this animation.
  29983. */
  29984. Animation.prototype.addEvent = function (event) {
  29985. this._events.push(event);
  29986. };
  29987. /**
  29988. * Remove all events found at the given frame
  29989. * @param frame
  29990. */
  29991. Animation.prototype.removeEvents = function (frame) {
  29992. for (var index = 0; index < this._events.length; index++) {
  29993. if (this._events[index].frame === frame) {
  29994. this._events.splice(index, 1);
  29995. index--;
  29996. }
  29997. }
  29998. };
  29999. Animation.prototype.createRange = function (name, from, to) {
  30000. // check name not already in use; could happen for bones after serialized
  30001. if (!this._ranges[name]) {
  30002. this._ranges[name] = new AnimationRange(name, from, to);
  30003. }
  30004. };
  30005. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30006. if (deleteFrames === void 0) { deleteFrames = true; }
  30007. if (this._ranges[name]) {
  30008. if (deleteFrames) {
  30009. var from = this._ranges[name].from;
  30010. var to = this._ranges[name].to;
  30011. // this loop MUST go high to low for multiple splices to work
  30012. for (var key = this._keys.length - 1; key >= 0; key--) {
  30013. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30014. this._keys.splice(key, 1);
  30015. }
  30016. }
  30017. }
  30018. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30019. }
  30020. };
  30021. Animation.prototype.getRange = function (name) {
  30022. return this._ranges[name];
  30023. };
  30024. Animation.prototype.reset = function () {
  30025. this._offsetsCache = {};
  30026. this._highLimitsCache = {};
  30027. this.currentFrame = 0;
  30028. this._blendingFactor = 0;
  30029. this._originalBlendValue = null;
  30030. };
  30031. Animation.prototype.isStopped = function () {
  30032. return this._stopped;
  30033. };
  30034. Animation.prototype.getKeys = function () {
  30035. return this._keys;
  30036. };
  30037. Animation.prototype.getHighestFrame = function () {
  30038. var ret = 0;
  30039. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30040. if (ret < this._keys[key].frame) {
  30041. ret = this._keys[key].frame;
  30042. }
  30043. }
  30044. return ret;
  30045. };
  30046. Animation.prototype.getEasingFunction = function () {
  30047. return this._easingFunction;
  30048. };
  30049. Animation.prototype.setEasingFunction = function (easingFunction) {
  30050. this._easingFunction = easingFunction;
  30051. };
  30052. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30053. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30054. };
  30055. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30056. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30057. };
  30058. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30059. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30060. };
  30061. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30062. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30063. };
  30064. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30065. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30066. };
  30067. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30068. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30069. };
  30070. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30071. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30072. };
  30073. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30074. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30075. };
  30076. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30077. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30078. };
  30079. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30080. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30081. };
  30082. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30083. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30084. };
  30085. Animation.prototype.clone = function () {
  30086. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30087. clone.enableBlending = this.enableBlending;
  30088. clone.blendingSpeed = this.blendingSpeed;
  30089. if (this._keys) {
  30090. clone.setKeys(this._keys);
  30091. }
  30092. if (this._ranges) {
  30093. clone._ranges = {};
  30094. for (var name in this._ranges) {
  30095. clone._ranges[name] = this._ranges[name].clone();
  30096. }
  30097. }
  30098. return clone;
  30099. };
  30100. Animation.prototype.setKeys = function (values) {
  30101. this._keys = values.slice(0);
  30102. this._offsetsCache = {};
  30103. this._highLimitsCache = {};
  30104. };
  30105. Animation.prototype._getKeyValue = function (value) {
  30106. if (typeof value === "function") {
  30107. return value();
  30108. }
  30109. return value;
  30110. };
  30111. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30112. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30113. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30114. }
  30115. this.currentFrame = currentFrame;
  30116. // Try to get a hash to find the right key
  30117. 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));
  30118. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30119. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30120. startKeyIndex--;
  30121. }
  30122. }
  30123. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30124. var endKey = this._keys[key + 1];
  30125. if (endKey.frame >= currentFrame) {
  30126. var startKey = this._keys[key];
  30127. var startValue = this._getKeyValue(startKey.value);
  30128. var endValue = this._getKeyValue(endKey.value);
  30129. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30130. var frameDelta = endKey.frame - startKey.frame;
  30131. // gradient : percent of currentFrame between the frame inf and the frame sup
  30132. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30133. // check for easingFunction and correction of gradient
  30134. if (this._easingFunction != null) {
  30135. gradient = this._easingFunction.ease(gradient);
  30136. }
  30137. switch (this.dataType) {
  30138. // Float
  30139. case Animation.ANIMATIONTYPE_FLOAT:
  30140. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30141. switch (loopMode) {
  30142. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30143. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30144. return floatValue;
  30145. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30146. return offsetValue * repeatCount + floatValue;
  30147. }
  30148. break;
  30149. // Quaternion
  30150. case Animation.ANIMATIONTYPE_QUATERNION:
  30151. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30152. switch (loopMode) {
  30153. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30154. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30155. return quatValue;
  30156. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30157. return quatValue.add(offsetValue.scale(repeatCount));
  30158. }
  30159. return quatValue;
  30160. // Vector3
  30161. case Animation.ANIMATIONTYPE_VECTOR3:
  30162. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30163. switch (loopMode) {
  30164. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30165. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30166. return vec3Value;
  30167. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30168. return vec3Value.add(offsetValue.scale(repeatCount));
  30169. }
  30170. // Vector2
  30171. case Animation.ANIMATIONTYPE_VECTOR2:
  30172. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30173. switch (loopMode) {
  30174. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30175. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30176. return vec2Value;
  30177. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30178. return vec2Value.add(offsetValue.scale(repeatCount));
  30179. }
  30180. // Size
  30181. case Animation.ANIMATIONTYPE_SIZE:
  30182. switch (loopMode) {
  30183. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30184. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30185. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30186. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30187. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30188. }
  30189. // Color3
  30190. case Animation.ANIMATIONTYPE_COLOR3:
  30191. switch (loopMode) {
  30192. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30193. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30194. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30195. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30196. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30197. }
  30198. // Matrix
  30199. case Animation.ANIMATIONTYPE_MATRIX:
  30200. switch (loopMode) {
  30201. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30202. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30203. if (this.allowMatricesInterpolation) {
  30204. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30205. }
  30206. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30207. return startValue;
  30208. }
  30209. default:
  30210. break;
  30211. }
  30212. break;
  30213. }
  30214. }
  30215. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30216. };
  30217. Animation.prototype.setValue = function (currentValue, blend) {
  30218. if (blend === void 0) { blend = false; }
  30219. // Set value
  30220. var path;
  30221. var destination;
  30222. if (this.targetPropertyPath.length > 1) {
  30223. var property = this._target[this.targetPropertyPath[0]];
  30224. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30225. property = property[this.targetPropertyPath[index]];
  30226. }
  30227. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30228. destination = property;
  30229. }
  30230. else {
  30231. path = this.targetPropertyPath[0];
  30232. destination = this._target;
  30233. }
  30234. // Blending
  30235. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30236. if (!this._originalBlendValue) {
  30237. if (destination[path].clone) {
  30238. this._originalBlendValue = destination[path].clone();
  30239. }
  30240. else {
  30241. this._originalBlendValue = destination[path];
  30242. }
  30243. }
  30244. if (this._originalBlendValue.prototype) {
  30245. if (this._originalBlendValue.prototype.Lerp) {
  30246. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30247. }
  30248. else {
  30249. destination[path] = currentValue;
  30250. }
  30251. }
  30252. else if (this._originalBlendValue.m) {
  30253. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30254. }
  30255. else {
  30256. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30257. }
  30258. this._blendingFactor += this.blendingSpeed;
  30259. }
  30260. else {
  30261. destination[path] = currentValue;
  30262. }
  30263. if (this._target.markAsDirty) {
  30264. this._target.markAsDirty(this.targetProperty);
  30265. }
  30266. };
  30267. Animation.prototype.goToFrame = function (frame) {
  30268. if (frame < this._keys[0].frame) {
  30269. frame = this._keys[0].frame;
  30270. }
  30271. else if (frame > this._keys[this._keys.length - 1].frame) {
  30272. frame = this._keys[this._keys.length - 1].frame;
  30273. }
  30274. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30275. this.setValue(currentValue);
  30276. };
  30277. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30278. if (blend === void 0) { blend = false; }
  30279. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30280. this._stopped = true;
  30281. return false;
  30282. }
  30283. var returnValue = true;
  30284. // Adding a start key at frame 0 if missing
  30285. if (this._keys[0].frame !== 0) {
  30286. var newKey = { frame: 0, value: this._keys[0].value };
  30287. this._keys.splice(0, 0, newKey);
  30288. }
  30289. // Check limits
  30290. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30291. from = this._keys[0].frame;
  30292. }
  30293. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30294. to = this._keys[this._keys.length - 1].frame;
  30295. }
  30296. //to and from cannot be the same key
  30297. if (from === to) {
  30298. from++;
  30299. }
  30300. // Compute ratio
  30301. var range = to - from;
  30302. var offsetValue;
  30303. // ratio represents the frame delta between from and to
  30304. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30305. var highLimitValue = 0;
  30306. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30307. returnValue = false;
  30308. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30309. }
  30310. else {
  30311. // Get max value if required
  30312. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30313. var keyOffset = to.toString() + from.toString();
  30314. if (!this._offsetsCache[keyOffset]) {
  30315. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30316. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30317. switch (this.dataType) {
  30318. // Float
  30319. case Animation.ANIMATIONTYPE_FLOAT:
  30320. this._offsetsCache[keyOffset] = toValue - fromValue;
  30321. break;
  30322. // Quaternion
  30323. case Animation.ANIMATIONTYPE_QUATERNION:
  30324. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30325. break;
  30326. // Vector3
  30327. case Animation.ANIMATIONTYPE_VECTOR3:
  30328. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30329. // Vector2
  30330. case Animation.ANIMATIONTYPE_VECTOR2:
  30331. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30332. // Size
  30333. case Animation.ANIMATIONTYPE_SIZE:
  30334. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30335. // Color3
  30336. case Animation.ANIMATIONTYPE_COLOR3:
  30337. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30338. default:
  30339. break;
  30340. }
  30341. this._highLimitsCache[keyOffset] = toValue;
  30342. }
  30343. highLimitValue = this._highLimitsCache[keyOffset];
  30344. offsetValue = this._offsetsCache[keyOffset];
  30345. }
  30346. }
  30347. if (offsetValue === undefined) {
  30348. switch (this.dataType) {
  30349. // Float
  30350. case Animation.ANIMATIONTYPE_FLOAT:
  30351. offsetValue = 0;
  30352. break;
  30353. // Quaternion
  30354. case Animation.ANIMATIONTYPE_QUATERNION:
  30355. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30356. break;
  30357. // Vector3
  30358. case Animation.ANIMATIONTYPE_VECTOR3:
  30359. offsetValue = BABYLON.Vector3.Zero();
  30360. break;
  30361. // Vector2
  30362. case Animation.ANIMATIONTYPE_VECTOR2:
  30363. offsetValue = BABYLON.Vector2.Zero();
  30364. break;
  30365. // Size
  30366. case Animation.ANIMATIONTYPE_SIZE:
  30367. offsetValue = BABYLON.Size.Zero();
  30368. break;
  30369. // Color3
  30370. case Animation.ANIMATIONTYPE_COLOR3:
  30371. offsetValue = BABYLON.Color3.Black();
  30372. }
  30373. }
  30374. // Compute value
  30375. var repeatCount = (ratio / range) >> 0;
  30376. var currentFrame = returnValue ? from + ratio % range : to;
  30377. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30378. // Set value
  30379. this.setValue(currentValue);
  30380. // Check events
  30381. for (var index = 0; index < this._events.length; index++) {
  30382. if (currentFrame >= this._events[index].frame) {
  30383. var event = this._events[index];
  30384. if (!event.isDone) {
  30385. // If event should be done only once, remove it.
  30386. if (event.onlyOnce) {
  30387. this._events.splice(index, 1);
  30388. index--;
  30389. }
  30390. event.isDone = true;
  30391. event.action();
  30392. } // Don't do anything if the event has already be done.
  30393. }
  30394. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30395. // reset event, the animation is looping
  30396. this._events[index].isDone = false;
  30397. }
  30398. }
  30399. if (!returnValue) {
  30400. this._stopped = true;
  30401. }
  30402. return returnValue;
  30403. };
  30404. Animation.prototype.serialize = function () {
  30405. var serializationObject = {};
  30406. serializationObject.name = this.name;
  30407. serializationObject.property = this.targetProperty;
  30408. serializationObject.framePerSecond = this.framePerSecond;
  30409. serializationObject.dataType = this.dataType;
  30410. serializationObject.loopBehavior = this.loopMode;
  30411. serializationObject.enableBlending = this.enableBlending;
  30412. serializationObject.blendingSpeed = this.blendingSpeed;
  30413. var dataType = this.dataType;
  30414. serializationObject.keys = [];
  30415. var keys = this.getKeys();
  30416. for (var index = 0; index < keys.length; index++) {
  30417. var animationKey = keys[index];
  30418. var key = {};
  30419. key.frame = animationKey.frame;
  30420. switch (dataType) {
  30421. case Animation.ANIMATIONTYPE_FLOAT:
  30422. key.values = [animationKey.value];
  30423. break;
  30424. case Animation.ANIMATIONTYPE_QUATERNION:
  30425. case Animation.ANIMATIONTYPE_MATRIX:
  30426. case Animation.ANIMATIONTYPE_VECTOR3:
  30427. case Animation.ANIMATIONTYPE_COLOR3:
  30428. key.values = animationKey.value.asArray();
  30429. break;
  30430. }
  30431. serializationObject.keys.push(key);
  30432. }
  30433. serializationObject.ranges = [];
  30434. for (var name in this._ranges) {
  30435. var range = {};
  30436. range.name = name;
  30437. range.from = this._ranges[name].from;
  30438. range.to = this._ranges[name].to;
  30439. serializationObject.ranges.push(range);
  30440. }
  30441. return serializationObject;
  30442. };
  30443. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30444. get: function () {
  30445. return Animation._ANIMATIONTYPE_FLOAT;
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30451. get: function () {
  30452. return Animation._ANIMATIONTYPE_VECTOR3;
  30453. },
  30454. enumerable: true,
  30455. configurable: true
  30456. });
  30457. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30458. get: function () {
  30459. return Animation._ANIMATIONTYPE_VECTOR2;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30465. get: function () {
  30466. return Animation._ANIMATIONTYPE_SIZE;
  30467. },
  30468. enumerable: true,
  30469. configurable: true
  30470. });
  30471. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30472. get: function () {
  30473. return Animation._ANIMATIONTYPE_QUATERNION;
  30474. },
  30475. enumerable: true,
  30476. configurable: true
  30477. });
  30478. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30479. get: function () {
  30480. return Animation._ANIMATIONTYPE_MATRIX;
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30486. get: function () {
  30487. return Animation._ANIMATIONTYPE_COLOR3;
  30488. },
  30489. enumerable: true,
  30490. configurable: true
  30491. });
  30492. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30493. get: function () {
  30494. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30495. },
  30496. enumerable: true,
  30497. configurable: true
  30498. });
  30499. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30500. get: function () {
  30501. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30502. },
  30503. enumerable: true,
  30504. configurable: true
  30505. });
  30506. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30507. get: function () {
  30508. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30509. },
  30510. enumerable: true,
  30511. configurable: true
  30512. });
  30513. Animation.Parse = function (parsedAnimation) {
  30514. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30515. var dataType = parsedAnimation.dataType;
  30516. var keys = [];
  30517. var data;
  30518. var index;
  30519. if (parsedAnimation.enableBlending) {
  30520. animation.enableBlending = parsedAnimation.enableBlending;
  30521. }
  30522. if (parsedAnimation.blendingSpeed) {
  30523. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30524. }
  30525. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30526. var key = parsedAnimation.keys[index];
  30527. switch (dataType) {
  30528. case Animation.ANIMATIONTYPE_FLOAT:
  30529. data = key.values[0];
  30530. break;
  30531. case Animation.ANIMATIONTYPE_QUATERNION:
  30532. data = BABYLON.Quaternion.FromArray(key.values);
  30533. break;
  30534. case Animation.ANIMATIONTYPE_MATRIX:
  30535. data = BABYLON.Matrix.FromArray(key.values);
  30536. break;
  30537. case Animation.ANIMATIONTYPE_COLOR3:
  30538. data = BABYLON.Color3.FromArray(key.values);
  30539. break;
  30540. case Animation.ANIMATIONTYPE_VECTOR3:
  30541. default:
  30542. data = BABYLON.Vector3.FromArray(key.values);
  30543. break;
  30544. }
  30545. keys.push({
  30546. frame: key.frame,
  30547. value: data
  30548. });
  30549. }
  30550. animation.setKeys(keys);
  30551. if (parsedAnimation.ranges) {
  30552. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30553. data = parsedAnimation.ranges[index];
  30554. animation.createRange(data.name, data.from, data.to);
  30555. }
  30556. }
  30557. return animation;
  30558. };
  30559. Animation.AppendSerializedAnimations = function (source, destination) {
  30560. if (source.animations) {
  30561. destination.animations = [];
  30562. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30563. var animation = source.animations[animationIndex];
  30564. destination.animations.push(animation.serialize());
  30565. }
  30566. }
  30567. };
  30568. return Animation;
  30569. }());
  30570. // Statics
  30571. Animation._ANIMATIONTYPE_FLOAT = 0;
  30572. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30573. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30574. Animation._ANIMATIONTYPE_MATRIX = 3;
  30575. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30576. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30577. Animation._ANIMATIONTYPE_SIZE = 6;
  30578. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30579. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30580. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30581. BABYLON.Animation = Animation;
  30582. })(BABYLON || (BABYLON = {}));
  30583. //# sourceMappingURL=babylon.animation.js.map
  30584. var BABYLON;
  30585. (function (BABYLON) {
  30586. var Animatable = (function () {
  30587. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30588. if (fromFrame === void 0) { fromFrame = 0; }
  30589. if (toFrame === void 0) { toFrame = 100; }
  30590. if (loopAnimation === void 0) { loopAnimation = false; }
  30591. if (speedRatio === void 0) { speedRatio = 1.0; }
  30592. this.target = target;
  30593. this.fromFrame = fromFrame;
  30594. this.toFrame = toFrame;
  30595. this.loopAnimation = loopAnimation;
  30596. this.speedRatio = speedRatio;
  30597. this.onAnimationEnd = onAnimationEnd;
  30598. this._localDelayOffset = null;
  30599. this._pausedDelay = null;
  30600. this._animations = new Array();
  30601. this._paused = false;
  30602. this.animationStarted = false;
  30603. if (animations) {
  30604. this.appendAnimations(target, animations);
  30605. }
  30606. this._scene = scene;
  30607. scene._activeAnimatables.push(this);
  30608. }
  30609. // Methods
  30610. Animatable.prototype.getAnimations = function () {
  30611. return this._animations;
  30612. };
  30613. Animatable.prototype.appendAnimations = function (target, animations) {
  30614. for (var index = 0; index < animations.length; index++) {
  30615. var animation = animations[index];
  30616. animation._target = target;
  30617. this._animations.push(animation);
  30618. }
  30619. };
  30620. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30621. var animations = this._animations;
  30622. for (var index = 0; index < animations.length; index++) {
  30623. if (animations[index].targetProperty === property) {
  30624. return animations[index];
  30625. }
  30626. }
  30627. return null;
  30628. };
  30629. Animatable.prototype.reset = function () {
  30630. var animations = this._animations;
  30631. for (var index = 0; index < animations.length; index++) {
  30632. animations[index].reset();
  30633. }
  30634. this._localDelayOffset = null;
  30635. this._pausedDelay = null;
  30636. };
  30637. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30638. var animations = this._animations;
  30639. for (var index = 0; index < animations.length; index++) {
  30640. animations[index].enableBlending = true;
  30641. animations[index].blendingSpeed = blendingSpeed;
  30642. }
  30643. };
  30644. Animatable.prototype.disableBlending = function () {
  30645. var animations = this._animations;
  30646. for (var index = 0; index < animations.length; index++) {
  30647. animations[index].enableBlending = false;
  30648. }
  30649. };
  30650. Animatable.prototype.goToFrame = function (frame) {
  30651. var animations = this._animations;
  30652. if (animations[0]) {
  30653. var fps = animations[0].framePerSecond;
  30654. var currentFrame = animations[0].currentFrame;
  30655. var adjustTime = frame - currentFrame;
  30656. var delay = adjustTime * 1000 / fps;
  30657. this._localDelayOffset -= delay;
  30658. }
  30659. for (var index = 0; index < animations.length; index++) {
  30660. animations[index].goToFrame(frame);
  30661. }
  30662. };
  30663. Animatable.prototype.pause = function () {
  30664. if (this._paused) {
  30665. return;
  30666. }
  30667. this._paused = true;
  30668. };
  30669. Animatable.prototype.restart = function () {
  30670. this._paused = false;
  30671. };
  30672. Animatable.prototype.stop = function (animationName) {
  30673. if (animationName) {
  30674. var idx = this._scene._activeAnimatables.indexOf(this);
  30675. if (idx > -1) {
  30676. var animations = this._animations;
  30677. for (var index = animations.length - 1; index >= 0; index--) {
  30678. if (typeof animationName === "string" && animations[index].name != animationName) {
  30679. continue;
  30680. }
  30681. animations[index].reset();
  30682. animations.splice(index, 1);
  30683. }
  30684. if (animations.length == 0) {
  30685. this._scene._activeAnimatables.splice(idx, 1);
  30686. if (this.onAnimationEnd) {
  30687. this.onAnimationEnd();
  30688. }
  30689. }
  30690. }
  30691. }
  30692. else {
  30693. var index = this._scene._activeAnimatables.indexOf(this);
  30694. if (index > -1) {
  30695. this._scene._activeAnimatables.splice(index, 1);
  30696. var animations = this._animations;
  30697. for (var index = 0; index < animations.length; index++) {
  30698. animations[index].reset();
  30699. }
  30700. if (this.onAnimationEnd) {
  30701. this.onAnimationEnd();
  30702. }
  30703. }
  30704. }
  30705. };
  30706. Animatable.prototype._animate = function (delay) {
  30707. if (this._paused) {
  30708. this.animationStarted = false;
  30709. if (this._pausedDelay === null) {
  30710. this._pausedDelay = delay;
  30711. }
  30712. return true;
  30713. }
  30714. if (this._localDelayOffset === null) {
  30715. this._localDelayOffset = delay;
  30716. }
  30717. else if (this._pausedDelay !== null) {
  30718. this._localDelayOffset += delay - this._pausedDelay;
  30719. this._pausedDelay = null;
  30720. }
  30721. // Animating
  30722. var running = false;
  30723. var animations = this._animations;
  30724. var index;
  30725. for (index = 0; index < animations.length; index++) {
  30726. var animation = animations[index];
  30727. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30728. running = running || isRunning;
  30729. }
  30730. this.animationStarted = running;
  30731. if (!running) {
  30732. // Remove from active animatables
  30733. index = this._scene._activeAnimatables.indexOf(this);
  30734. this._scene._activeAnimatables.splice(index, 1);
  30735. }
  30736. if (!running && this.onAnimationEnd) {
  30737. this.onAnimationEnd();
  30738. this.onAnimationEnd = null;
  30739. }
  30740. return running;
  30741. };
  30742. return Animatable;
  30743. }());
  30744. BABYLON.Animatable = Animatable;
  30745. })(BABYLON || (BABYLON = {}));
  30746. //# sourceMappingURL=babylon.animatable.js.map
  30747. var BABYLON;
  30748. (function (BABYLON) {
  30749. var EasingFunction = (function () {
  30750. function EasingFunction() {
  30751. // Properties
  30752. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30753. }
  30754. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30755. get: function () {
  30756. return EasingFunction._EASINGMODE_EASEIN;
  30757. },
  30758. enumerable: true,
  30759. configurable: true
  30760. });
  30761. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30762. get: function () {
  30763. return EasingFunction._EASINGMODE_EASEOUT;
  30764. },
  30765. enumerable: true,
  30766. configurable: true
  30767. });
  30768. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30769. get: function () {
  30770. return EasingFunction._EASINGMODE_EASEINOUT;
  30771. },
  30772. enumerable: true,
  30773. configurable: true
  30774. });
  30775. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30776. var n = Math.min(Math.max(easingMode, 0), 2);
  30777. this._easingMode = n;
  30778. };
  30779. EasingFunction.prototype.getEasingMode = function () {
  30780. return this._easingMode;
  30781. };
  30782. EasingFunction.prototype.easeInCore = function (gradient) {
  30783. throw new Error('You must implement this method');
  30784. };
  30785. EasingFunction.prototype.ease = function (gradient) {
  30786. switch (this._easingMode) {
  30787. case EasingFunction.EASINGMODE_EASEIN:
  30788. return this.easeInCore(gradient);
  30789. case EasingFunction.EASINGMODE_EASEOUT:
  30790. return (1 - this.easeInCore(1 - gradient));
  30791. }
  30792. if (gradient >= 0.5) {
  30793. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30794. }
  30795. return (this.easeInCore(gradient * 2) * 0.5);
  30796. };
  30797. return EasingFunction;
  30798. }());
  30799. //Statics
  30800. EasingFunction._EASINGMODE_EASEIN = 0;
  30801. EasingFunction._EASINGMODE_EASEOUT = 1;
  30802. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30803. BABYLON.EasingFunction = EasingFunction;
  30804. var CircleEase = (function (_super) {
  30805. __extends(CircleEase, _super);
  30806. function CircleEase() {
  30807. return _super !== null && _super.apply(this, arguments) || this;
  30808. }
  30809. CircleEase.prototype.easeInCore = function (gradient) {
  30810. gradient = Math.max(0, Math.min(1, gradient));
  30811. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30812. };
  30813. return CircleEase;
  30814. }(EasingFunction));
  30815. BABYLON.CircleEase = CircleEase;
  30816. var BackEase = (function (_super) {
  30817. __extends(BackEase, _super);
  30818. function BackEase(amplitude) {
  30819. if (amplitude === void 0) { amplitude = 1; }
  30820. var _this = _super.call(this) || this;
  30821. _this.amplitude = amplitude;
  30822. return _this;
  30823. }
  30824. BackEase.prototype.easeInCore = function (gradient) {
  30825. var num = Math.max(0, this.amplitude);
  30826. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30827. };
  30828. return BackEase;
  30829. }(EasingFunction));
  30830. BABYLON.BackEase = BackEase;
  30831. var BounceEase = (function (_super) {
  30832. __extends(BounceEase, _super);
  30833. function BounceEase(bounces, bounciness) {
  30834. if (bounces === void 0) { bounces = 3; }
  30835. if (bounciness === void 0) { bounciness = 2; }
  30836. var _this = _super.call(this) || this;
  30837. _this.bounces = bounces;
  30838. _this.bounciness = bounciness;
  30839. return _this;
  30840. }
  30841. BounceEase.prototype.easeInCore = function (gradient) {
  30842. var y = Math.max(0.0, this.bounces);
  30843. var bounciness = this.bounciness;
  30844. if (bounciness <= 1.0) {
  30845. bounciness = 1.001;
  30846. }
  30847. var num9 = Math.pow(bounciness, y);
  30848. var num5 = 1.0 - bounciness;
  30849. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30850. var num15 = gradient * num4;
  30851. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30852. var num3 = Math.floor(num65);
  30853. var num13 = num3 + 1.0;
  30854. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30855. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30856. var num7 = (num8 + num12) * 0.5;
  30857. var num6 = gradient - num7;
  30858. var num2 = num7 - num8;
  30859. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30860. };
  30861. return BounceEase;
  30862. }(EasingFunction));
  30863. BABYLON.BounceEase = BounceEase;
  30864. var CubicEase = (function (_super) {
  30865. __extends(CubicEase, _super);
  30866. function CubicEase() {
  30867. return _super !== null && _super.apply(this, arguments) || this;
  30868. }
  30869. CubicEase.prototype.easeInCore = function (gradient) {
  30870. return (gradient * gradient * gradient);
  30871. };
  30872. return CubicEase;
  30873. }(EasingFunction));
  30874. BABYLON.CubicEase = CubicEase;
  30875. var ElasticEase = (function (_super) {
  30876. __extends(ElasticEase, _super);
  30877. function ElasticEase(oscillations, springiness) {
  30878. if (oscillations === void 0) { oscillations = 3; }
  30879. if (springiness === void 0) { springiness = 3; }
  30880. var _this = _super.call(this) || this;
  30881. _this.oscillations = oscillations;
  30882. _this.springiness = springiness;
  30883. return _this;
  30884. }
  30885. ElasticEase.prototype.easeInCore = function (gradient) {
  30886. var num2;
  30887. var num3 = Math.max(0.0, this.oscillations);
  30888. var num = Math.max(0.0, this.springiness);
  30889. if (num == 0) {
  30890. num2 = gradient;
  30891. }
  30892. else {
  30893. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30894. }
  30895. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30896. };
  30897. return ElasticEase;
  30898. }(EasingFunction));
  30899. BABYLON.ElasticEase = ElasticEase;
  30900. var ExponentialEase = (function (_super) {
  30901. __extends(ExponentialEase, _super);
  30902. function ExponentialEase(exponent) {
  30903. if (exponent === void 0) { exponent = 2; }
  30904. var _this = _super.call(this) || this;
  30905. _this.exponent = exponent;
  30906. return _this;
  30907. }
  30908. ExponentialEase.prototype.easeInCore = function (gradient) {
  30909. if (this.exponent <= 0) {
  30910. return gradient;
  30911. }
  30912. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30913. };
  30914. return ExponentialEase;
  30915. }(EasingFunction));
  30916. BABYLON.ExponentialEase = ExponentialEase;
  30917. var PowerEase = (function (_super) {
  30918. __extends(PowerEase, _super);
  30919. function PowerEase(power) {
  30920. if (power === void 0) { power = 2; }
  30921. var _this = _super.call(this) || this;
  30922. _this.power = power;
  30923. return _this;
  30924. }
  30925. PowerEase.prototype.easeInCore = function (gradient) {
  30926. var y = Math.max(0.0, this.power);
  30927. return Math.pow(gradient, y);
  30928. };
  30929. return PowerEase;
  30930. }(EasingFunction));
  30931. BABYLON.PowerEase = PowerEase;
  30932. var QuadraticEase = (function (_super) {
  30933. __extends(QuadraticEase, _super);
  30934. function QuadraticEase() {
  30935. return _super !== null && _super.apply(this, arguments) || this;
  30936. }
  30937. QuadraticEase.prototype.easeInCore = function (gradient) {
  30938. return (gradient * gradient);
  30939. };
  30940. return QuadraticEase;
  30941. }(EasingFunction));
  30942. BABYLON.QuadraticEase = QuadraticEase;
  30943. var QuarticEase = (function (_super) {
  30944. __extends(QuarticEase, _super);
  30945. function QuarticEase() {
  30946. return _super !== null && _super.apply(this, arguments) || this;
  30947. }
  30948. QuarticEase.prototype.easeInCore = function (gradient) {
  30949. return (gradient * gradient * gradient * gradient);
  30950. };
  30951. return QuarticEase;
  30952. }(EasingFunction));
  30953. BABYLON.QuarticEase = QuarticEase;
  30954. var QuinticEase = (function (_super) {
  30955. __extends(QuinticEase, _super);
  30956. function QuinticEase() {
  30957. return _super !== null && _super.apply(this, arguments) || this;
  30958. }
  30959. QuinticEase.prototype.easeInCore = function (gradient) {
  30960. return (gradient * gradient * gradient * gradient * gradient);
  30961. };
  30962. return QuinticEase;
  30963. }(EasingFunction));
  30964. BABYLON.QuinticEase = QuinticEase;
  30965. var SineEase = (function (_super) {
  30966. __extends(SineEase, _super);
  30967. function SineEase() {
  30968. return _super !== null && _super.apply(this, arguments) || this;
  30969. }
  30970. SineEase.prototype.easeInCore = function (gradient) {
  30971. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30972. };
  30973. return SineEase;
  30974. }(EasingFunction));
  30975. BABYLON.SineEase = SineEase;
  30976. var BezierCurveEase = (function (_super) {
  30977. __extends(BezierCurveEase, _super);
  30978. function BezierCurveEase(x1, y1, x2, y2) {
  30979. if (x1 === void 0) { x1 = 0; }
  30980. if (y1 === void 0) { y1 = 0; }
  30981. if (x2 === void 0) { x2 = 1; }
  30982. if (y2 === void 0) { y2 = 1; }
  30983. var _this = _super.call(this) || this;
  30984. _this.x1 = x1;
  30985. _this.y1 = y1;
  30986. _this.x2 = x2;
  30987. _this.y2 = y2;
  30988. return _this;
  30989. }
  30990. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30991. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30992. };
  30993. return BezierCurveEase;
  30994. }(EasingFunction));
  30995. BABYLON.BezierCurveEase = BezierCurveEase;
  30996. })(BABYLON || (BABYLON = {}));
  30997. //# sourceMappingURL=babylon.easing.js.map
  30998. var BABYLON;
  30999. (function (BABYLON) {
  31000. BABYLON.CameraInputTypes = {};
  31001. var CameraInputsManager = (function () {
  31002. function CameraInputsManager(camera) {
  31003. this.attached = {};
  31004. this.camera = camera;
  31005. this.checkInputs = function () { };
  31006. }
  31007. CameraInputsManager.prototype.add = function (input) {
  31008. var type = input.getSimpleName();
  31009. if (this.attached[type]) {
  31010. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  31011. return;
  31012. }
  31013. this.attached[type] = input;
  31014. input.camera = this.camera;
  31015. //for checkInputs, we are dynamically creating a function
  31016. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  31017. if (input.checkInputs) {
  31018. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31019. }
  31020. if (this.attachedElement) {
  31021. input.attachControl(this.attachedElement);
  31022. }
  31023. };
  31024. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31025. for (var cam in this.attached) {
  31026. var input = this.attached[cam];
  31027. if (input === inputToRemove) {
  31028. input.detachControl(this.attachedElement);
  31029. delete this.attached[cam];
  31030. this.rebuildInputCheck();
  31031. }
  31032. }
  31033. };
  31034. CameraInputsManager.prototype.removeByType = function (inputType) {
  31035. for (var cam in this.attached) {
  31036. var input = this.attached[cam];
  31037. if (input.getTypeName() === inputType) {
  31038. input.detachControl(this.attachedElement);
  31039. delete this.attached[cam];
  31040. this.rebuildInputCheck();
  31041. }
  31042. }
  31043. };
  31044. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31045. var current = this.checkInputs;
  31046. return function () {
  31047. current();
  31048. fn();
  31049. };
  31050. };
  31051. CameraInputsManager.prototype.attachInput = function (input) {
  31052. input.attachControl(this.attachedElement, this.noPreventDefault);
  31053. };
  31054. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31055. if (this.attachedElement) {
  31056. return;
  31057. }
  31058. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31059. this.attachedElement = element;
  31060. this.noPreventDefault = noPreventDefault;
  31061. for (var cam in this.attached) {
  31062. var input = this.attached[cam];
  31063. this.attached[cam].attachControl(element, noPreventDefault);
  31064. }
  31065. };
  31066. CameraInputsManager.prototype.detachElement = function (element) {
  31067. if (this.attachedElement !== element) {
  31068. return;
  31069. }
  31070. for (var cam in this.attached) {
  31071. var input = this.attached[cam];
  31072. this.attached[cam].detachControl(element);
  31073. }
  31074. this.attachedElement = null;
  31075. };
  31076. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31077. this.checkInputs = function () { };
  31078. for (var cam in this.attached) {
  31079. var input = this.attached[cam];
  31080. if (input.checkInputs) {
  31081. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31082. }
  31083. }
  31084. };
  31085. CameraInputsManager.prototype.clear = function () {
  31086. if (this.attachedElement) {
  31087. this.detachElement(this.attachedElement);
  31088. }
  31089. this.attached = {};
  31090. this.attachedElement = null;
  31091. this.checkInputs = function () { };
  31092. };
  31093. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31094. var inputs = {};
  31095. for (var cam in this.attached) {
  31096. var input = this.attached[cam];
  31097. var res = BABYLON.SerializationHelper.Serialize(input);
  31098. inputs[input.getTypeName()] = res;
  31099. }
  31100. serializedCamera.inputsmgr = inputs;
  31101. };
  31102. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31103. var parsedInputs = parsedCamera.inputsmgr;
  31104. if (parsedInputs) {
  31105. this.clear();
  31106. for (var n in parsedInputs) {
  31107. var construct = BABYLON.CameraInputTypes[n];
  31108. if (construct) {
  31109. var parsedinput = parsedInputs[n];
  31110. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31111. this.add(input);
  31112. }
  31113. }
  31114. }
  31115. else {
  31116. //2016-03-08 this part is for managing backward compatibility
  31117. for (var n in this.attached) {
  31118. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31119. if (construct) {
  31120. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31121. this.remove(this.attached[n]);
  31122. this.add(input);
  31123. }
  31124. }
  31125. }
  31126. };
  31127. return CameraInputsManager;
  31128. }());
  31129. BABYLON.CameraInputsManager = CameraInputsManager;
  31130. })(BABYLON || (BABYLON = {}));
  31131. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31132. /// <reference path="babylon.camera.ts" />
  31133. var BABYLON;
  31134. (function (BABYLON) {
  31135. var TargetCamera = (function (_super) {
  31136. __extends(TargetCamera, _super);
  31137. function TargetCamera(name, position, scene) {
  31138. var _this = _super.call(this, name, position, scene) || this;
  31139. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31140. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31141. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31142. _this.speed = 2.0;
  31143. _this.noRotationConstraint = false;
  31144. _this.lockedTarget = null;
  31145. _this._currentTarget = BABYLON.Vector3.Zero();
  31146. _this._viewMatrix = BABYLON.Matrix.Zero();
  31147. _this._camMatrix = BABYLON.Matrix.Zero();
  31148. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31149. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31150. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31151. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31152. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31153. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31154. _this._tempMatrix = BABYLON.Matrix.Zero();
  31155. return _this;
  31156. }
  31157. TargetCamera.prototype.getFrontPosition = function (distance) {
  31158. var direction = this.getTarget().subtract(this.position);
  31159. direction.normalize();
  31160. direction.scaleInPlace(distance);
  31161. return this.globalPosition.add(direction);
  31162. };
  31163. TargetCamera.prototype._getLockedTargetPosition = function () {
  31164. if (!this.lockedTarget) {
  31165. return null;
  31166. }
  31167. if (this.lockedTarget.absolutePosition) {
  31168. this.lockedTarget.computeWorldMatrix();
  31169. }
  31170. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31171. };
  31172. // Cache
  31173. TargetCamera.prototype._initCache = function () {
  31174. _super.prototype._initCache.call(this);
  31175. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31176. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31177. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31178. };
  31179. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31180. if (!ignoreParentClass) {
  31181. _super.prototype._updateCache.call(this);
  31182. }
  31183. var lockedTargetPosition = this._getLockedTargetPosition();
  31184. if (!lockedTargetPosition) {
  31185. this._cache.lockedTarget = null;
  31186. }
  31187. else {
  31188. if (!this._cache.lockedTarget) {
  31189. this._cache.lockedTarget = lockedTargetPosition.clone();
  31190. }
  31191. else {
  31192. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31193. }
  31194. }
  31195. this._cache.rotation.copyFrom(this.rotation);
  31196. if (this.rotationQuaternion)
  31197. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31198. };
  31199. // Synchronized
  31200. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31201. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31202. return false;
  31203. }
  31204. var lockedTargetPosition = this._getLockedTargetPosition();
  31205. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31206. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31207. };
  31208. // Methods
  31209. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31210. var engine = this.getEngine();
  31211. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31212. };
  31213. // Target
  31214. TargetCamera.prototype.setTarget = function (target) {
  31215. this.upVector.normalize();
  31216. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31217. this._camMatrix.invert();
  31218. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31219. var vDir = target.subtract(this.position);
  31220. if (vDir.x >= 0.0) {
  31221. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31222. }
  31223. else {
  31224. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31225. }
  31226. this.rotation.z = 0;
  31227. if (isNaN(this.rotation.x)) {
  31228. this.rotation.x = 0;
  31229. }
  31230. if (isNaN(this.rotation.y)) {
  31231. this.rotation.y = 0;
  31232. }
  31233. if (isNaN(this.rotation.z)) {
  31234. this.rotation.z = 0;
  31235. }
  31236. if (this.rotationQuaternion) {
  31237. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31238. }
  31239. };
  31240. /**
  31241. * Return the current target position of the camera. This value is expressed in local space.
  31242. */
  31243. TargetCamera.prototype.getTarget = function () {
  31244. return this._currentTarget;
  31245. };
  31246. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31247. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31248. };
  31249. TargetCamera.prototype._updatePosition = function () {
  31250. if (this.parent) {
  31251. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31252. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31253. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31254. return;
  31255. }
  31256. this.position.addInPlace(this.cameraDirection);
  31257. };
  31258. TargetCamera.prototype._checkInputs = function () {
  31259. var needToMove = this._decideIfNeedsToMove();
  31260. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31261. // Move
  31262. if (needToMove) {
  31263. this._updatePosition();
  31264. }
  31265. // Rotate
  31266. if (needToRotate) {
  31267. this.rotation.x += this.cameraRotation.x;
  31268. this.rotation.y += this.cameraRotation.y;
  31269. //rotate, if quaternion is set and rotation was used
  31270. if (this.rotationQuaternion) {
  31271. var len = this.rotation.lengthSquared();
  31272. if (len) {
  31273. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31274. }
  31275. }
  31276. if (!this.noRotationConstraint) {
  31277. var limit = (Math.PI / 2) * 0.95;
  31278. if (this.rotation.x > limit)
  31279. this.rotation.x = limit;
  31280. if (this.rotation.x < -limit)
  31281. this.rotation.x = -limit;
  31282. }
  31283. }
  31284. // Inertia
  31285. if (needToMove) {
  31286. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31287. this.cameraDirection.x = 0;
  31288. }
  31289. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31290. this.cameraDirection.y = 0;
  31291. }
  31292. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31293. this.cameraDirection.z = 0;
  31294. }
  31295. this.cameraDirection.scaleInPlace(this.inertia);
  31296. }
  31297. if (needToRotate) {
  31298. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31299. this.cameraRotation.x = 0;
  31300. }
  31301. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31302. this.cameraRotation.y = 0;
  31303. }
  31304. this.cameraRotation.scaleInPlace(this.inertia);
  31305. }
  31306. _super.prototype._checkInputs.call(this);
  31307. };
  31308. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31309. if (this.rotationQuaternion) {
  31310. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31311. //update the up vector!
  31312. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31313. }
  31314. else {
  31315. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31316. }
  31317. };
  31318. TargetCamera.prototype._getViewMatrix = function () {
  31319. if (!this.lockedTarget) {
  31320. // Compute
  31321. this._updateCameraRotationMatrix();
  31322. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31323. // Computing target and final matrix
  31324. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31325. }
  31326. else {
  31327. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31328. }
  31329. if (this.getScene().useRightHandedSystem) {
  31330. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31331. }
  31332. else {
  31333. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31334. }
  31335. return this._viewMatrix;
  31336. };
  31337. /**
  31338. * @override
  31339. * Override Camera.createRigCamera
  31340. */
  31341. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31342. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31343. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31344. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31345. if (!this.rotationQuaternion) {
  31346. this.rotationQuaternion = new BABYLON.Quaternion();
  31347. }
  31348. rigCamera._cameraRigParams = {};
  31349. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31350. }
  31351. return rigCamera;
  31352. }
  31353. return null;
  31354. };
  31355. /**
  31356. * @override
  31357. * Override Camera._updateRigCameras
  31358. */
  31359. TargetCamera.prototype._updateRigCameras = function () {
  31360. var camLeft = this._rigCameras[0];
  31361. var camRight = this._rigCameras[1];
  31362. switch (this.cameraRigMode) {
  31363. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31364. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31365. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31366. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31367. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31368. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31369. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31370. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31371. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31372. camLeft.setTarget(this.getTarget());
  31373. camRight.setTarget(this.getTarget());
  31374. break;
  31375. case BABYLON.Camera.RIG_MODE_VR:
  31376. if (camLeft.rotationQuaternion) {
  31377. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31378. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31379. }
  31380. else {
  31381. camLeft.rotation.copyFrom(this.rotation);
  31382. camRight.rotation.copyFrom(this.rotation);
  31383. }
  31384. camLeft.position.copyFrom(this.position);
  31385. camRight.position.copyFrom(this.position);
  31386. break;
  31387. }
  31388. _super.prototype._updateRigCameras.call(this);
  31389. };
  31390. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31391. if (!this._rigCamTransformMatrix) {
  31392. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31393. }
  31394. var target = this.getTarget();
  31395. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31396. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31397. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31398. };
  31399. TargetCamera.prototype.getClassName = function () {
  31400. return "TargetCamera";
  31401. };
  31402. return TargetCamera;
  31403. }(BABYLON.Camera));
  31404. __decorate([
  31405. BABYLON.serializeAsVector3()
  31406. ], TargetCamera.prototype, "rotation", void 0);
  31407. __decorate([
  31408. BABYLON.serialize()
  31409. ], TargetCamera.prototype, "speed", void 0);
  31410. __decorate([
  31411. BABYLON.serializeAsMeshReference("lockedTargetId")
  31412. ], TargetCamera.prototype, "lockedTarget", void 0);
  31413. BABYLON.TargetCamera = TargetCamera;
  31414. })(BABYLON || (BABYLON = {}));
  31415. //# sourceMappingURL=babylon.targetCamera.js.map
  31416. var BABYLON;
  31417. (function (BABYLON) {
  31418. var ArcRotateCameraKeyboardMoveInput = (function () {
  31419. function ArcRotateCameraKeyboardMoveInput() {
  31420. this._keys = [];
  31421. this.keysUp = [38];
  31422. this.keysDown = [40];
  31423. this.keysLeft = [37];
  31424. this.keysRight = [39];
  31425. }
  31426. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31427. var _this = this;
  31428. element.tabIndex = 1;
  31429. this._onKeyDown = function (evt) {
  31430. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31431. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31432. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31433. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31434. var index = _this._keys.indexOf(evt.keyCode);
  31435. if (index === -1) {
  31436. _this._keys.push(evt.keyCode);
  31437. }
  31438. if (evt.preventDefault) {
  31439. if (!noPreventDefault) {
  31440. evt.preventDefault();
  31441. }
  31442. }
  31443. }
  31444. };
  31445. this._onKeyUp = function (evt) {
  31446. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31447. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31448. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31449. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31450. var index = _this._keys.indexOf(evt.keyCode);
  31451. if (index >= 0) {
  31452. _this._keys.splice(index, 1);
  31453. }
  31454. if (evt.preventDefault) {
  31455. if (!noPreventDefault) {
  31456. evt.preventDefault();
  31457. }
  31458. }
  31459. }
  31460. };
  31461. this._onLostFocus = function () {
  31462. _this._keys = [];
  31463. };
  31464. element.addEventListener("keydown", this._onKeyDown, false);
  31465. element.addEventListener("keyup", this._onKeyUp, false);
  31466. BABYLON.Tools.RegisterTopRootEvents([
  31467. { name: "blur", handler: this._onLostFocus }
  31468. ]);
  31469. };
  31470. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31471. if (element) {
  31472. element.removeEventListener("keydown", this._onKeyDown);
  31473. element.removeEventListener("keyup", this._onKeyUp);
  31474. }
  31475. BABYLON.Tools.UnregisterTopRootEvents([
  31476. { name: "blur", handler: this._onLostFocus }
  31477. ]);
  31478. this._keys = [];
  31479. this._onKeyDown = null;
  31480. this._onKeyUp = null;
  31481. this._onLostFocus = null;
  31482. };
  31483. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31484. if (this._onKeyDown) {
  31485. var camera = this.camera;
  31486. for (var index = 0; index < this._keys.length; index++) {
  31487. var keyCode = this._keys[index];
  31488. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31489. camera.inertialAlphaOffset -= 0.01;
  31490. }
  31491. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31492. camera.inertialBetaOffset -= 0.01;
  31493. }
  31494. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31495. camera.inertialAlphaOffset += 0.01;
  31496. }
  31497. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31498. camera.inertialBetaOffset += 0.01;
  31499. }
  31500. }
  31501. }
  31502. };
  31503. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31504. return "ArcRotateCameraKeyboardMoveInput";
  31505. };
  31506. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31507. return "keyboard";
  31508. };
  31509. return ArcRotateCameraKeyboardMoveInput;
  31510. }());
  31511. __decorate([
  31512. BABYLON.serialize()
  31513. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31514. __decorate([
  31515. BABYLON.serialize()
  31516. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31517. __decorate([
  31518. BABYLON.serialize()
  31519. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31520. __decorate([
  31521. BABYLON.serialize()
  31522. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31523. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31524. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31525. })(BABYLON || (BABYLON = {}));
  31526. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31527. var BABYLON;
  31528. (function (BABYLON) {
  31529. var ArcRotateCameraMouseWheelInput = (function () {
  31530. function ArcRotateCameraMouseWheelInput() {
  31531. this.wheelPrecision = 3.0;
  31532. }
  31533. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31534. var _this = this;
  31535. this._wheel = function (p, s) {
  31536. //sanity check - this should be a PointerWheel event.
  31537. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31538. return;
  31539. var event = p.event;
  31540. var delta = 0;
  31541. if (event.wheelDelta) {
  31542. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31543. }
  31544. else if (event.detail) {
  31545. delta = -event.detail / _this.wheelPrecision;
  31546. }
  31547. if (delta)
  31548. _this.camera.inertialRadiusOffset += delta;
  31549. if (event.preventDefault) {
  31550. if (!noPreventDefault) {
  31551. event.preventDefault();
  31552. }
  31553. }
  31554. };
  31555. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31556. };
  31557. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31558. if (this._observer && element) {
  31559. this.camera.getScene().onPointerObservable.remove(this._observer);
  31560. this._observer = null;
  31561. this._wheel = null;
  31562. }
  31563. };
  31564. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  31565. return "ArcRotateCameraMouseWheelInput";
  31566. };
  31567. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31568. return "mousewheel";
  31569. };
  31570. return ArcRotateCameraMouseWheelInput;
  31571. }());
  31572. __decorate([
  31573. BABYLON.serialize()
  31574. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31575. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31576. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31577. })(BABYLON || (BABYLON = {}));
  31578. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31579. var BABYLON;
  31580. (function (BABYLON) {
  31581. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31582. var ArcRotateCameraPointersInput = (function () {
  31583. function ArcRotateCameraPointersInput() {
  31584. this.buttons = [0, 1, 2];
  31585. this.angularSensibilityX = 1000.0;
  31586. this.angularSensibilityY = 1000.0;
  31587. this.pinchPrecision = 6.0;
  31588. this.panningSensibility = 50.0;
  31589. this._isPanClick = false;
  31590. this.pinchInwards = true;
  31591. }
  31592. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31593. var _this = this;
  31594. var engine = this.camera.getEngine();
  31595. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31596. var pointA, pointB;
  31597. var previousPinchDistance = 0;
  31598. this._pointerInput = function (p, s) {
  31599. var evt = p.event;
  31600. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31601. return;
  31602. }
  31603. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31604. try {
  31605. evt.srcElement.setPointerCapture(evt.pointerId);
  31606. }
  31607. catch (e) {
  31608. //Nothing to do with the error. Execution will continue.
  31609. }
  31610. // Manage panning with pan button click
  31611. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31612. // manage pointers
  31613. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31614. if (pointA === undefined) {
  31615. pointA = cacheSoloPointer;
  31616. }
  31617. else if (pointB === undefined) {
  31618. pointB = cacheSoloPointer;
  31619. }
  31620. if (!noPreventDefault) {
  31621. evt.preventDefault();
  31622. element.focus();
  31623. }
  31624. }
  31625. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31626. try {
  31627. evt.srcElement.releasePointerCapture(evt.pointerId);
  31628. }
  31629. catch (e) {
  31630. //Nothing to do with the error.
  31631. }
  31632. cacheSoloPointer = null;
  31633. previousPinchDistance = 0;
  31634. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31635. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31636. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31637. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31638. pointA = pointB = undefined;
  31639. if (!noPreventDefault) {
  31640. evt.preventDefault();
  31641. }
  31642. }
  31643. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31644. if (!noPreventDefault) {
  31645. evt.preventDefault();
  31646. }
  31647. // One button down
  31648. if (pointA && pointB === undefined) {
  31649. if (_this.panningSensibility !== 0 &&
  31650. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31651. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31652. _this.camera
  31653. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31654. _this.camera
  31655. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31656. }
  31657. else {
  31658. var offsetX = evt.clientX - cacheSoloPointer.x;
  31659. var offsetY = evt.clientY - cacheSoloPointer.y;
  31660. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31661. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31662. }
  31663. cacheSoloPointer.x = evt.clientX;
  31664. cacheSoloPointer.y = evt.clientY;
  31665. }
  31666. else if (pointA && pointB) {
  31667. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31668. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31669. ed.x = evt.clientX;
  31670. ed.y = evt.clientY;
  31671. var direction = _this.pinchInwards ? 1 : -1;
  31672. var distX = pointA.x - pointB.x;
  31673. var distY = pointA.y - pointB.y;
  31674. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31675. if (previousPinchDistance === 0) {
  31676. previousPinchDistance = pinchSquaredDistance;
  31677. return;
  31678. }
  31679. if (pinchSquaredDistance !== previousPinchDistance) {
  31680. _this.camera
  31681. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31682. (_this.pinchPrecision *
  31683. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31684. direction);
  31685. previousPinchDistance = pinchSquaredDistance;
  31686. }
  31687. }
  31688. }
  31689. };
  31690. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31691. this._onContextMenu = function (evt) {
  31692. evt.preventDefault();
  31693. };
  31694. if (!this.camera._useCtrlForPanning) {
  31695. element.addEventListener("contextmenu", this._onContextMenu, false);
  31696. }
  31697. this._onLostFocus = function () {
  31698. //this._keys = [];
  31699. pointA = pointB = undefined;
  31700. previousPinchDistance = 0;
  31701. cacheSoloPointer = null;
  31702. };
  31703. this._onMouseMove = function (evt) {
  31704. if (!engine.isPointerLock) {
  31705. return;
  31706. }
  31707. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31708. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31709. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31710. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31711. if (!noPreventDefault) {
  31712. evt.preventDefault();
  31713. }
  31714. };
  31715. this._onGestureStart = function (e) {
  31716. if (window.MSGesture === undefined) {
  31717. return;
  31718. }
  31719. if (!_this._MSGestureHandler) {
  31720. _this._MSGestureHandler = new MSGesture();
  31721. _this._MSGestureHandler.target = element;
  31722. }
  31723. _this._MSGestureHandler.addPointer(e.pointerId);
  31724. };
  31725. this._onGesture = function (e) {
  31726. _this.camera.radius *= e.scale;
  31727. if (e.preventDefault) {
  31728. if (!noPreventDefault) {
  31729. e.stopPropagation();
  31730. e.preventDefault();
  31731. }
  31732. }
  31733. };
  31734. element.addEventListener("mousemove", this._onMouseMove, false);
  31735. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31736. element.addEventListener("MSGestureChange", this._onGesture, false);
  31737. BABYLON.Tools.RegisterTopRootEvents([
  31738. { name: "blur", handler: this._onLostFocus }
  31739. ]);
  31740. };
  31741. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31742. if (element && this._observer) {
  31743. this.camera.getScene().onPointerObservable.remove(this._observer);
  31744. this._observer = null;
  31745. element.removeEventListener("contextmenu", this._onContextMenu);
  31746. element.removeEventListener("mousemove", this._onMouseMove);
  31747. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31748. element.removeEventListener("MSGestureChange", this._onGesture);
  31749. this._isPanClick = false;
  31750. this.pinchInwards = true;
  31751. this._onMouseMove = null;
  31752. this._onGestureStart = null;
  31753. this._onGesture = null;
  31754. this._MSGestureHandler = null;
  31755. this._onLostFocus = null;
  31756. this._onContextMenu = null;
  31757. }
  31758. BABYLON.Tools.UnregisterTopRootEvents([
  31759. { name: "blur", handler: this._onLostFocus }
  31760. ]);
  31761. };
  31762. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  31763. return "ArcRotateCameraPointersInput";
  31764. };
  31765. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31766. return "pointers";
  31767. };
  31768. return ArcRotateCameraPointersInput;
  31769. }());
  31770. __decorate([
  31771. BABYLON.serialize()
  31772. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31773. __decorate([
  31774. BABYLON.serialize()
  31775. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31776. __decorate([
  31777. BABYLON.serialize()
  31778. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31779. __decorate([
  31780. BABYLON.serialize()
  31781. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31782. __decorate([
  31783. BABYLON.serialize()
  31784. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31785. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31786. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31787. })(BABYLON || (BABYLON = {}));
  31788. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31789. /// <reference path="babylon.targetCamera.ts" />
  31790. /// <reference path="..\Tools\babylon.tools.ts" />
  31791. var BABYLON;
  31792. (function (BABYLON) {
  31793. var ArcRotateCamera = (function (_super) {
  31794. __extends(ArcRotateCamera, _super);
  31795. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31796. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31797. _this.inertialAlphaOffset = 0;
  31798. _this.inertialBetaOffset = 0;
  31799. _this.inertialRadiusOffset = 0;
  31800. _this.lowerAlphaLimit = null;
  31801. _this.upperAlphaLimit = null;
  31802. _this.lowerBetaLimit = 0.01;
  31803. _this.upperBetaLimit = Math.PI;
  31804. _this.lowerRadiusLimit = null;
  31805. _this.upperRadiusLimit = null;
  31806. _this.inertialPanningX = 0;
  31807. _this.inertialPanningY = 0;
  31808. _this.panningInertia = 0.9;
  31809. //-- end properties for backward compatibility for inputs
  31810. _this.zoomOnFactor = 1;
  31811. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31812. _this.allowUpsideDown = true;
  31813. _this._viewMatrix = new BABYLON.Matrix();
  31814. // Panning
  31815. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31816. _this.checkCollisions = false;
  31817. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31818. _this._previousPosition = BABYLON.Vector3.Zero();
  31819. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31820. _this._newPosition = BABYLON.Vector3.Zero();
  31821. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31822. if (collidedMesh === void 0) { collidedMesh = null; }
  31823. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31824. newPosition.multiplyInPlace(_this._collider.radius);
  31825. }
  31826. if (!collidedMesh) {
  31827. _this._previousPosition.copyFrom(_this.position);
  31828. }
  31829. else {
  31830. _this.setPosition(newPosition);
  31831. if (_this.onCollide) {
  31832. _this.onCollide(collidedMesh);
  31833. }
  31834. }
  31835. // Recompute because of constraints
  31836. var cosa = Math.cos(_this.alpha);
  31837. var sina = Math.sin(_this.alpha);
  31838. var cosb = Math.cos(_this.beta);
  31839. var sinb = Math.sin(_this.beta);
  31840. if (sinb === 0) {
  31841. sinb = 0.0001;
  31842. }
  31843. var target = _this._getTargetPosition();
  31844. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31845. _this.position.copyFrom(_this._newPosition);
  31846. var up = _this.upVector;
  31847. if (_this.allowUpsideDown && _this.beta < 0) {
  31848. up = up.clone();
  31849. up = up.negate();
  31850. }
  31851. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31852. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31853. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31854. _this._collisionTriggered = false;
  31855. };
  31856. _this._target = BABYLON.Vector3.Zero();
  31857. if (target) {
  31858. _this.setTarget(target);
  31859. }
  31860. _this.alpha = alpha;
  31861. _this.beta = beta;
  31862. _this.radius = radius;
  31863. _this.getViewMatrix();
  31864. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31865. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31866. return _this;
  31867. }
  31868. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31869. get: function () {
  31870. return this._target;
  31871. },
  31872. set: function (value) {
  31873. this.setTarget(value);
  31874. },
  31875. enumerable: true,
  31876. configurable: true
  31877. });
  31878. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31879. //-- begin properties for backward compatibility for inputs
  31880. get: function () {
  31881. var pointers = this.inputs.attached["pointers"];
  31882. if (pointers)
  31883. return pointers.angularSensibilityX;
  31884. },
  31885. set: function (value) {
  31886. var pointers = this.inputs.attached["pointers"];
  31887. if (pointers) {
  31888. pointers.angularSensibilityX = value;
  31889. }
  31890. },
  31891. enumerable: true,
  31892. configurable: true
  31893. });
  31894. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31895. get: function () {
  31896. var pointers = this.inputs.attached["pointers"];
  31897. if (pointers)
  31898. return pointers.angularSensibilityY;
  31899. },
  31900. set: function (value) {
  31901. var pointers = this.inputs.attached["pointers"];
  31902. if (pointers) {
  31903. pointers.angularSensibilityY = value;
  31904. }
  31905. },
  31906. enumerable: true,
  31907. configurable: true
  31908. });
  31909. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31910. get: function () {
  31911. var pointers = this.inputs.attached["pointers"];
  31912. if (pointers)
  31913. return pointers.pinchPrecision;
  31914. },
  31915. set: function (value) {
  31916. var pointers = this.inputs.attached["pointers"];
  31917. if (pointers) {
  31918. pointers.pinchPrecision = value;
  31919. }
  31920. },
  31921. enumerable: true,
  31922. configurable: true
  31923. });
  31924. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31925. get: function () {
  31926. var pointers = this.inputs.attached["pointers"];
  31927. if (pointers)
  31928. return pointers.panningSensibility;
  31929. },
  31930. set: function (value) {
  31931. var pointers = this.inputs.attached["pointers"];
  31932. if (pointers) {
  31933. pointers.panningSensibility = value;
  31934. }
  31935. },
  31936. enumerable: true,
  31937. configurable: true
  31938. });
  31939. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31940. get: function () {
  31941. var keyboard = this.inputs.attached["keyboard"];
  31942. if (keyboard)
  31943. return keyboard.keysUp;
  31944. },
  31945. set: function (value) {
  31946. var keyboard = this.inputs.attached["keyboard"];
  31947. if (keyboard)
  31948. keyboard.keysUp = value;
  31949. },
  31950. enumerable: true,
  31951. configurable: true
  31952. });
  31953. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31954. get: function () {
  31955. var keyboard = this.inputs.attached["keyboard"];
  31956. if (keyboard)
  31957. return keyboard.keysDown;
  31958. },
  31959. set: function (value) {
  31960. var keyboard = this.inputs.attached["keyboard"];
  31961. if (keyboard)
  31962. keyboard.keysDown = value;
  31963. },
  31964. enumerable: true,
  31965. configurable: true
  31966. });
  31967. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31968. get: function () {
  31969. var keyboard = this.inputs.attached["keyboard"];
  31970. if (keyboard)
  31971. return keyboard.keysLeft;
  31972. },
  31973. set: function (value) {
  31974. var keyboard = this.inputs.attached["keyboard"];
  31975. if (keyboard)
  31976. keyboard.keysLeft = value;
  31977. },
  31978. enumerable: true,
  31979. configurable: true
  31980. });
  31981. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31982. get: function () {
  31983. var keyboard = this.inputs.attached["keyboard"];
  31984. if (keyboard)
  31985. return keyboard.keysRight;
  31986. },
  31987. set: function (value) {
  31988. var keyboard = this.inputs.attached["keyboard"];
  31989. if (keyboard)
  31990. keyboard.keysRight = value;
  31991. },
  31992. enumerable: true,
  31993. configurable: true
  31994. });
  31995. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31996. get: function () {
  31997. var mousewheel = this.inputs.attached["mousewheel"];
  31998. if (mousewheel)
  31999. return mousewheel.wheelPrecision;
  32000. },
  32001. set: function (value) {
  32002. var mousewheel = this.inputs.attached["mousewheel"];
  32003. if (mousewheel)
  32004. mousewheel.wheelPrecision = value;
  32005. },
  32006. enumerable: true,
  32007. configurable: true
  32008. });
  32009. // Cache
  32010. ArcRotateCamera.prototype._initCache = function () {
  32011. _super.prototype._initCache.call(this);
  32012. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  32013. this._cache.alpha = undefined;
  32014. this._cache.beta = undefined;
  32015. this._cache.radius = undefined;
  32016. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  32017. };
  32018. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  32019. if (!ignoreParentClass) {
  32020. _super.prototype._updateCache.call(this);
  32021. }
  32022. this._cache._target.copyFrom(this._getTargetPosition());
  32023. this._cache.alpha = this.alpha;
  32024. this._cache.beta = this.beta;
  32025. this._cache.radius = this.radius;
  32026. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32027. };
  32028. ArcRotateCamera.prototype._getTargetPosition = function () {
  32029. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32030. var pos = this._targetHost.getAbsolutePosition();
  32031. if (this._targetBoundingCenter) {
  32032. pos.addToRef(this._targetBoundingCenter, this._target);
  32033. }
  32034. else {
  32035. this._target.copyFrom(pos);
  32036. }
  32037. }
  32038. return this._target;
  32039. };
  32040. // Synchronized
  32041. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32042. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32043. return false;
  32044. return this._cache._target.equals(this._getTargetPosition())
  32045. && this._cache.alpha === this.alpha
  32046. && this._cache.beta === this.beta
  32047. && this._cache.radius === this.radius
  32048. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32049. };
  32050. // Methods
  32051. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32052. var _this = this;
  32053. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32054. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32055. this._useCtrlForPanning = useCtrlForPanning;
  32056. this._panningMouseButton = panningMouseButton;
  32057. this.inputs.attachElement(element, noPreventDefault);
  32058. this._reset = function () {
  32059. _this.inertialAlphaOffset = 0;
  32060. _this.inertialBetaOffset = 0;
  32061. _this.inertialRadiusOffset = 0;
  32062. };
  32063. };
  32064. ArcRotateCamera.prototype.detachControl = function (element) {
  32065. this.inputs.detachElement(element);
  32066. if (this._reset) {
  32067. this._reset();
  32068. }
  32069. };
  32070. ArcRotateCamera.prototype._checkInputs = function () {
  32071. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32072. if (this._collisionTriggered) {
  32073. return;
  32074. }
  32075. this.inputs.checkInputs();
  32076. // Inertia
  32077. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32078. if (this.getScene().useRightHandedSystem) {
  32079. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32080. }
  32081. else {
  32082. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32083. }
  32084. this.beta += this.inertialBetaOffset;
  32085. this.radius -= this.inertialRadiusOffset;
  32086. this.inertialAlphaOffset *= this.inertia;
  32087. this.inertialBetaOffset *= this.inertia;
  32088. this.inertialRadiusOffset *= this.inertia;
  32089. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  32090. this.inertialAlphaOffset = 0;
  32091. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  32092. this.inertialBetaOffset = 0;
  32093. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32094. this.inertialRadiusOffset = 0;
  32095. }
  32096. // Panning inertia
  32097. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32098. if (!this._localDirection) {
  32099. this._localDirection = BABYLON.Vector3.Zero();
  32100. this._transformedDirection = BABYLON.Vector3.Zero();
  32101. }
  32102. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32103. this._localDirection.multiplyInPlace(this.panningAxis);
  32104. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32105. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32106. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32107. if (!this.panningAxis.y) {
  32108. this._transformedDirection.y = 0;
  32109. }
  32110. if (!this._targetHost) {
  32111. this._target.addInPlace(this._transformedDirection);
  32112. }
  32113. this.inertialPanningX *= this.panningInertia;
  32114. this.inertialPanningY *= this.panningInertia;
  32115. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32116. this.inertialPanningX = 0;
  32117. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32118. this.inertialPanningY = 0;
  32119. }
  32120. // Limits
  32121. this._checkLimits();
  32122. _super.prototype._checkInputs.call(this);
  32123. };
  32124. ArcRotateCamera.prototype._checkLimits = function () {
  32125. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32126. if (this.allowUpsideDown && this.beta > Math.PI) {
  32127. this.beta = this.beta - (2 * Math.PI);
  32128. }
  32129. }
  32130. else {
  32131. if (this.beta < this.lowerBetaLimit) {
  32132. this.beta = this.lowerBetaLimit;
  32133. }
  32134. }
  32135. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32136. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32137. this.beta = this.beta + (2 * Math.PI);
  32138. }
  32139. }
  32140. else {
  32141. if (this.beta > this.upperBetaLimit) {
  32142. this.beta = this.upperBetaLimit;
  32143. }
  32144. }
  32145. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32146. this.alpha = this.lowerAlphaLimit;
  32147. }
  32148. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32149. this.alpha = this.upperAlphaLimit;
  32150. }
  32151. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32152. this.radius = this.lowerRadiusLimit;
  32153. }
  32154. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32155. this.radius = this.upperRadiusLimit;
  32156. }
  32157. };
  32158. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32159. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32160. this.radius = radiusv3.length();
  32161. // Alpha
  32162. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32163. if (radiusv3.z < 0) {
  32164. this.alpha = 2 * Math.PI - this.alpha;
  32165. }
  32166. // Beta
  32167. this.beta = Math.acos(radiusv3.y / this.radius);
  32168. this._checkLimits();
  32169. };
  32170. ArcRotateCamera.prototype.setPosition = function (position) {
  32171. if (this.position.equals(position)) {
  32172. return;
  32173. }
  32174. this.position.copyFrom(position);
  32175. this.rebuildAnglesAndRadius();
  32176. };
  32177. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32178. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32179. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32180. if (target.getBoundingInfo) {
  32181. if (toBoundingCenter) {
  32182. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32183. }
  32184. else {
  32185. this._targetBoundingCenter = null;
  32186. }
  32187. this._targetHost = target;
  32188. this._target = this._getTargetPosition();
  32189. }
  32190. else {
  32191. var newTarget = target;
  32192. var currentTarget = this._getTargetPosition();
  32193. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32194. return;
  32195. }
  32196. this._target = newTarget;
  32197. this._targetBoundingCenter = null;
  32198. }
  32199. this.rebuildAnglesAndRadius();
  32200. };
  32201. ArcRotateCamera.prototype._getViewMatrix = function () {
  32202. // Compute
  32203. var cosa = Math.cos(this.alpha);
  32204. var sina = Math.sin(this.alpha);
  32205. var cosb = Math.cos(this.beta);
  32206. var sinb = Math.sin(this.beta);
  32207. if (sinb === 0) {
  32208. sinb = 0.0001;
  32209. }
  32210. var target = this._getTargetPosition();
  32211. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32212. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32213. if (!this._collider) {
  32214. this._collider = new BABYLON.Collider();
  32215. }
  32216. this._collider.radius = this.collisionRadius;
  32217. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32218. this._collisionTriggered = true;
  32219. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32220. }
  32221. else {
  32222. this.position.copyFrom(this._newPosition);
  32223. var up = this.upVector;
  32224. if (this.allowUpsideDown && sinb < 0) {
  32225. up = up.clone();
  32226. up = up.negate();
  32227. }
  32228. if (this.getScene().useRightHandedSystem) {
  32229. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32230. }
  32231. else {
  32232. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32233. }
  32234. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32235. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32236. }
  32237. this._currentTarget = target;
  32238. return this._viewMatrix;
  32239. };
  32240. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32241. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32242. meshes = meshes || this.getScene().meshes;
  32243. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32244. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32245. this.radius = distance * this.zoomOnFactor;
  32246. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32247. };
  32248. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32249. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32250. var meshesOrMinMaxVector;
  32251. var distance;
  32252. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32253. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32254. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32255. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32256. }
  32257. else {
  32258. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32259. distance = meshesOrMinMaxVectorAndDistance.distance;
  32260. }
  32261. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32262. if (!doNotUpdateMaxZ) {
  32263. this.maxZ = distance * 2;
  32264. }
  32265. };
  32266. /**
  32267. * @override
  32268. * Override Camera.createRigCamera
  32269. */
  32270. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32271. var alphaShift;
  32272. switch (this.cameraRigMode) {
  32273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32276. case BABYLON.Camera.RIG_MODE_VR:
  32277. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32278. break;
  32279. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32280. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32281. break;
  32282. }
  32283. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32284. rigCam._cameraRigParams = {};
  32285. return rigCam;
  32286. };
  32287. /**
  32288. * @override
  32289. * Override Camera._updateRigCameras
  32290. */
  32291. ArcRotateCamera.prototype._updateRigCameras = function () {
  32292. var camLeft = this._rigCameras[0];
  32293. var camRight = this._rigCameras[1];
  32294. camLeft.beta = camRight.beta = this.beta;
  32295. camLeft.radius = camRight.radius = this.radius;
  32296. switch (this.cameraRigMode) {
  32297. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32298. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32299. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32300. case BABYLON.Camera.RIG_MODE_VR:
  32301. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32302. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32303. break;
  32304. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32305. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32306. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32307. break;
  32308. }
  32309. _super.prototype._updateRigCameras.call(this);
  32310. };
  32311. ArcRotateCamera.prototype.dispose = function () {
  32312. this.inputs.clear();
  32313. _super.prototype.dispose.call(this);
  32314. };
  32315. ArcRotateCamera.prototype.getClassName = function () {
  32316. return "ArcRotateCamera";
  32317. };
  32318. return ArcRotateCamera;
  32319. }(BABYLON.TargetCamera));
  32320. __decorate([
  32321. BABYLON.serialize()
  32322. ], ArcRotateCamera.prototype, "alpha", void 0);
  32323. __decorate([
  32324. BABYLON.serialize()
  32325. ], ArcRotateCamera.prototype, "beta", void 0);
  32326. __decorate([
  32327. BABYLON.serialize()
  32328. ], ArcRotateCamera.prototype, "radius", void 0);
  32329. __decorate([
  32330. BABYLON.serializeAsVector3("target")
  32331. ], ArcRotateCamera.prototype, "_target", void 0);
  32332. __decorate([
  32333. BABYLON.serialize()
  32334. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32335. __decorate([
  32336. BABYLON.serialize()
  32337. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32338. __decorate([
  32339. BABYLON.serialize()
  32340. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32341. __decorate([
  32342. BABYLON.serialize()
  32343. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32344. __decorate([
  32345. BABYLON.serialize()
  32346. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32347. __decorate([
  32348. BABYLON.serialize()
  32349. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32350. __decorate([
  32351. BABYLON.serialize()
  32352. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32353. __decorate([
  32354. BABYLON.serialize()
  32355. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32356. __decorate([
  32357. BABYLON.serialize()
  32358. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32359. __decorate([
  32360. BABYLON.serialize()
  32361. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32362. __decorate([
  32363. BABYLON.serialize()
  32364. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32365. __decorate([
  32366. BABYLON.serialize()
  32367. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32368. __decorate([
  32369. BABYLON.serialize()
  32370. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32371. __decorate([
  32372. BABYLON.serialize()
  32373. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32374. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32375. })(BABYLON || (BABYLON = {}));
  32376. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32377. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32378. var BABYLON;
  32379. (function (BABYLON) {
  32380. var ArcRotateCameraInputsManager = (function (_super) {
  32381. __extends(ArcRotateCameraInputsManager, _super);
  32382. function ArcRotateCameraInputsManager(camera) {
  32383. return _super.call(this, camera) || this;
  32384. }
  32385. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32386. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32387. return this;
  32388. };
  32389. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32390. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32391. return this;
  32392. };
  32393. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32394. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32395. return this;
  32396. };
  32397. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32398. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32399. return this;
  32400. };
  32401. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32402. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32403. return this;
  32404. };
  32405. return ArcRotateCameraInputsManager;
  32406. }(BABYLON.CameraInputsManager));
  32407. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32408. })(BABYLON || (BABYLON = {}));
  32409. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32410. var BABYLON;
  32411. (function (BABYLON) {
  32412. var CubeTexture = (function (_super) {
  32413. __extends(CubeTexture, _super);
  32414. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  32415. if (onLoad === void 0) { onLoad = null; }
  32416. if (onError === void 0) { onError = null; }
  32417. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32418. var _this = _super.call(this, scene) || this;
  32419. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32420. _this.name = rootUrl;
  32421. _this.url = rootUrl;
  32422. _this._noMipmap = noMipmap;
  32423. _this.hasAlpha = false;
  32424. _this._format = format;
  32425. if (!rootUrl && !files) {
  32426. return _this;
  32427. }
  32428. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32429. if (!files) {
  32430. if (!extensions) {
  32431. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32432. }
  32433. files = [];
  32434. for (var index = 0; index < extensions.length; index++) {
  32435. files.push(rootUrl + extensions[index]);
  32436. }
  32437. _this._extensions = extensions;
  32438. }
  32439. _this._files = files;
  32440. if (!_this._texture) {
  32441. if (!scene.useDelayedTextureLoading) {
  32442. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  32443. }
  32444. else {
  32445. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32446. }
  32447. }
  32448. else if (onLoad) {
  32449. if (_this._texture.isReady) {
  32450. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32451. }
  32452. else {
  32453. _this._texture.onLoadedCallbacks.push(onLoad);
  32454. }
  32455. }
  32456. _this.isCube = true;
  32457. _this._textureMatrix = BABYLON.Matrix.Identity();
  32458. return _this;
  32459. }
  32460. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32461. return new CubeTexture("", scene, null, noMipmap, files);
  32462. };
  32463. // Methods
  32464. CubeTexture.prototype.delayLoad = function () {
  32465. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32466. return;
  32467. }
  32468. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32469. this._texture = this._getFromCache(this.url, this._noMipmap);
  32470. if (!this._texture) {
  32471. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32472. }
  32473. };
  32474. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32475. return this._textureMatrix;
  32476. };
  32477. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32478. var texture = BABYLON.SerializationHelper.Parse(function () {
  32479. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32480. }, parsedTexture, scene);
  32481. // Animations
  32482. if (parsedTexture.animations) {
  32483. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32484. var parsedAnimation = parsedTexture.animations[animationIndex];
  32485. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32486. }
  32487. }
  32488. return texture;
  32489. };
  32490. CubeTexture.prototype.clone = function () {
  32491. var _this = this;
  32492. return BABYLON.SerializationHelper.Clone(function () {
  32493. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  32494. }, this);
  32495. };
  32496. return CubeTexture;
  32497. }(BABYLON.BaseTexture));
  32498. BABYLON.CubeTexture = CubeTexture;
  32499. })(BABYLON || (BABYLON = {}));
  32500. //# sourceMappingURL=babylon.cubeTexture.js.map
  32501. var BABYLON;
  32502. (function (BABYLON) {
  32503. var RenderTargetTexture = (function (_super) {
  32504. __extends(RenderTargetTexture, _super);
  32505. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  32506. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  32507. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32508. if (isCube === void 0) { isCube = false; }
  32509. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32510. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32511. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  32512. if (isMulti === void 0) { isMulti = false; }
  32513. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  32514. _this.isCube = isCube;
  32515. /**
  32516. * Use this list to define the list of mesh you want to render.
  32517. */
  32518. _this.renderList = new Array();
  32519. _this.renderParticles = true;
  32520. _this.renderSprites = false;
  32521. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  32522. // Events
  32523. /**
  32524. * An event triggered when the texture is unbind.
  32525. * @type {BABYLON.Observable}
  32526. */
  32527. _this.onAfterUnbindObservable = new BABYLON.Observable();
  32528. /**
  32529. * An event triggered before rendering the texture
  32530. * @type {BABYLON.Observable}
  32531. */
  32532. _this.onBeforeRenderObservable = new BABYLON.Observable();
  32533. /**
  32534. * An event triggered after rendering the texture
  32535. * @type {BABYLON.Observable}
  32536. */
  32537. _this.onAfterRenderObservable = new BABYLON.Observable();
  32538. /**
  32539. * An event triggered after the texture clear
  32540. * @type {BABYLON.Observable}
  32541. */
  32542. _this.onClearObservable = new BABYLON.Observable();
  32543. _this._currentRefreshId = -1;
  32544. _this._refreshRate = 1;
  32545. _this._samples = 1;
  32546. _this.name = name;
  32547. _this.isRenderTarget = true;
  32548. _this._size = size;
  32549. _this._generateMipMaps = generateMipMaps;
  32550. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  32551. // Rendering groups
  32552. _this._renderingManager = new BABYLON.RenderingManager(scene);
  32553. if (isMulti) {
  32554. return _this;
  32555. }
  32556. _this._renderTargetOptions = {
  32557. generateMipMaps: generateMipMaps,
  32558. type: type,
  32559. samplingMode: samplingMode,
  32560. generateDepthBuffer: generateDepthBuffer,
  32561. generateStencilBuffer: generateStencilBuffer
  32562. };
  32563. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32564. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32565. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32566. }
  32567. if (isCube) {
  32568. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  32569. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  32570. _this._textureMatrix = BABYLON.Matrix.Identity();
  32571. }
  32572. else {
  32573. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  32574. }
  32575. return _this;
  32576. }
  32577. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  32578. get: function () {
  32579. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  32580. },
  32581. enumerable: true,
  32582. configurable: true
  32583. });
  32584. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  32585. get: function () {
  32586. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  32587. },
  32588. enumerable: true,
  32589. configurable: true
  32590. });
  32591. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  32592. get: function () {
  32593. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  32594. },
  32595. enumerable: true,
  32596. configurable: true
  32597. });
  32598. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  32599. set: function (callback) {
  32600. if (this._onAfterUnbindObserver) {
  32601. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  32602. }
  32603. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  32604. },
  32605. enumerable: true,
  32606. configurable: true
  32607. });
  32608. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  32609. set: function (callback) {
  32610. if (this._onBeforeRenderObserver) {
  32611. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32612. }
  32613. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32614. },
  32615. enumerable: true,
  32616. configurable: true
  32617. });
  32618. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  32619. set: function (callback) {
  32620. if (this._onAfterRenderObserver) {
  32621. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32622. }
  32623. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32624. },
  32625. enumerable: true,
  32626. configurable: true
  32627. });
  32628. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  32629. set: function (callback) {
  32630. if (this._onClearObserver) {
  32631. this.onClearObservable.remove(this._onClearObserver);
  32632. }
  32633. this._onClearObserver = this.onClearObservable.add(callback);
  32634. },
  32635. enumerable: true,
  32636. configurable: true
  32637. });
  32638. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  32639. get: function () {
  32640. return this._renderTargetOptions;
  32641. },
  32642. enumerable: true,
  32643. configurable: true
  32644. });
  32645. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  32646. get: function () {
  32647. return this._samples;
  32648. },
  32649. set: function (value) {
  32650. if (this._samples === value) {
  32651. return;
  32652. }
  32653. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  32654. },
  32655. enumerable: true,
  32656. configurable: true
  32657. });
  32658. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  32659. this._currentRefreshId = -1;
  32660. };
  32661. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  32662. get: function () {
  32663. return this._refreshRate;
  32664. },
  32665. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  32666. set: function (value) {
  32667. this._refreshRate = value;
  32668. this.resetRefreshCounter();
  32669. },
  32670. enumerable: true,
  32671. configurable: true
  32672. });
  32673. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  32674. if (!this._postProcessManager) {
  32675. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  32676. this._postProcesses = new Array();
  32677. }
  32678. this._postProcesses.push(postProcess);
  32679. this._postProcesses[0].autoClear = false;
  32680. };
  32681. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  32682. if (!this._postProcesses) {
  32683. return;
  32684. }
  32685. if (dispose) {
  32686. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  32687. var postProcess = _a[_i];
  32688. postProcess.dispose();
  32689. postProcess = null;
  32690. }
  32691. }
  32692. this._postProcesses = [];
  32693. };
  32694. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  32695. if (!this._postProcesses) {
  32696. return;
  32697. }
  32698. var index = this._postProcesses.indexOf(postProcess);
  32699. if (index === -1) {
  32700. return;
  32701. }
  32702. this._postProcesses.splice(index, 1);
  32703. if (this._postProcesses.length > 0) {
  32704. this._postProcesses[0].autoClear = false;
  32705. }
  32706. };
  32707. RenderTargetTexture.prototype._shouldRender = function () {
  32708. if (this._currentRefreshId === -1) {
  32709. this._currentRefreshId = 1;
  32710. return true;
  32711. }
  32712. if (this.refreshRate === this._currentRefreshId) {
  32713. this._currentRefreshId = 1;
  32714. return true;
  32715. }
  32716. this._currentRefreshId++;
  32717. return false;
  32718. };
  32719. RenderTargetTexture.prototype.isReady = function () {
  32720. if (!this.getScene().renderTargetsEnabled) {
  32721. return false;
  32722. }
  32723. return _super.prototype.isReady.call(this);
  32724. };
  32725. RenderTargetTexture.prototype.getRenderSize = function () {
  32726. return this._size;
  32727. };
  32728. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  32729. get: function () {
  32730. return true;
  32731. },
  32732. enumerable: true,
  32733. configurable: true
  32734. });
  32735. RenderTargetTexture.prototype.scale = function (ratio) {
  32736. var newSize = this._size * ratio;
  32737. this.resize(newSize);
  32738. };
  32739. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  32740. if (this.isCube) {
  32741. return this._textureMatrix;
  32742. }
  32743. return _super.prototype.getReflectionTextureMatrix.call(this);
  32744. };
  32745. RenderTargetTexture.prototype.resize = function (size) {
  32746. this.releaseInternalTexture();
  32747. if (this.isCube) {
  32748. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  32749. }
  32750. else {
  32751. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  32752. }
  32753. };
  32754. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  32755. var scene = this.getScene();
  32756. var engine = scene.getEngine();
  32757. if (this.useCameraPostProcesses !== undefined) {
  32758. useCameraPostProcess = this.useCameraPostProcesses;
  32759. }
  32760. if (this._waitingRenderList) {
  32761. this.renderList = [];
  32762. for (var index = 0; index < this._waitingRenderList.length; index++) {
  32763. var id = this._waitingRenderList[index];
  32764. this.renderList.push(scene.getMeshByID(id));
  32765. }
  32766. delete this._waitingRenderList;
  32767. }
  32768. // Is predicate defined?
  32769. if (this.renderListPredicate) {
  32770. this.renderList.splice(0); // Clear previous renderList
  32771. var sceneMeshes = this.getScene().meshes;
  32772. for (var index = 0; index < sceneMeshes.length; index++) {
  32773. var mesh = sceneMeshes[index];
  32774. if (this.renderListPredicate(mesh)) {
  32775. this.renderList.push(mesh);
  32776. }
  32777. }
  32778. }
  32779. if (this.renderList && this.renderList.length === 0) {
  32780. return;
  32781. }
  32782. // Set custom projection.
  32783. // Needs to be before binding to prevent changing the aspect ratio.
  32784. var camera;
  32785. if (this.activeCamera) {
  32786. camera = this.activeCamera;
  32787. engine.setViewport(this.activeCamera.viewport);
  32788. if (this.activeCamera !== scene.activeCamera) {
  32789. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  32790. }
  32791. }
  32792. else {
  32793. camera = scene.activeCamera;
  32794. engine.setViewport(scene.activeCamera.viewport);
  32795. }
  32796. // Prepare renderingManager
  32797. this._renderingManager.reset();
  32798. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  32799. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  32800. var sceneRenderId = scene.getRenderId();
  32801. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  32802. var mesh = currentRenderList[meshIndex];
  32803. if (mesh) {
  32804. if (!mesh.isReady()) {
  32805. // Reset _currentRefreshId
  32806. this.resetRefreshCounter();
  32807. continue;
  32808. }
  32809. mesh._preActivateForIntermediateRendering(sceneRenderId);
  32810. var isMasked = void 0;
  32811. if (!this.renderList) {
  32812. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  32813. }
  32814. else {
  32815. isMasked = false;
  32816. }
  32817. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  32818. mesh._activate(sceneRenderId);
  32819. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32820. var subMesh = mesh.subMeshes[subIndex];
  32821. scene._activeIndices.addCount(subMesh.indexCount, false);
  32822. this._renderingManager.dispatch(subMesh);
  32823. }
  32824. }
  32825. }
  32826. }
  32827. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  32828. var particleSystem = scene.particleSystems[particleIndex];
  32829. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  32830. continue;
  32831. }
  32832. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  32833. this._renderingManager.dispatchParticles(particleSystem);
  32834. }
  32835. }
  32836. if (this.isCube) {
  32837. for (var face = 0; face < 6; face++) {
  32838. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32839. scene.incrementRenderId();
  32840. scene.resetCachedMaterial();
  32841. }
  32842. }
  32843. else {
  32844. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32845. }
  32846. this.onAfterUnbindObservable.notifyObservers(this);
  32847. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  32848. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  32849. }
  32850. engine.setViewport(scene.activeCamera.viewport);
  32851. scene.resetCachedMaterial();
  32852. };
  32853. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  32854. var _this = this;
  32855. var scene = this.getScene();
  32856. var engine = scene.getEngine();
  32857. // Bind
  32858. if (this._postProcessManager) {
  32859. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  32860. }
  32861. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  32862. if (this.isCube) {
  32863. engine.bindFramebuffer(this._texture, faceIndex);
  32864. }
  32865. else {
  32866. engine.bindFramebuffer(this._texture);
  32867. }
  32868. }
  32869. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  32870. // Clear
  32871. if (this.onClearObservable.hasObservers()) {
  32872. this.onClearObservable.notifyObservers(engine);
  32873. }
  32874. else {
  32875. engine.clear(scene.clearColor, true, true, true);
  32876. }
  32877. if (!this._doNotChangeAspectRatio) {
  32878. scene.updateTransformMatrix(true);
  32879. }
  32880. // Render
  32881. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  32882. if (this._postProcessManager) {
  32883. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  32884. }
  32885. else if (useCameraPostProcess) {
  32886. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  32887. }
  32888. if (!this._doNotChangeAspectRatio) {
  32889. scene.updateTransformMatrix(true);
  32890. }
  32891. // Dump ?
  32892. if (dumpForDebug) {
  32893. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  32894. }
  32895. // Unbind
  32896. if (!this.isCube || faceIndex === 5) {
  32897. if (this.isCube) {
  32898. if (faceIndex === 5) {
  32899. engine.generateMipMapsForCubemap(this._texture);
  32900. }
  32901. }
  32902. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  32903. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  32904. });
  32905. }
  32906. else {
  32907. this.onAfterRenderObservable.notifyObservers(faceIndex);
  32908. }
  32909. };
  32910. /**
  32911. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  32912. * This allowed control for front to back rendering or reversly depending of the special needs.
  32913. *
  32914. * @param renderingGroupId The rendering group id corresponding to its index
  32915. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  32916. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  32917. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  32918. */
  32919. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  32920. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  32921. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  32922. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  32923. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  32924. };
  32925. /**
  32926. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  32927. *
  32928. * @param renderingGroupId The rendering group id corresponding to its index
  32929. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  32930. */
  32931. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  32932. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  32933. };
  32934. RenderTargetTexture.prototype.clone = function () {
  32935. var textureSize = this.getSize();
  32936. 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);
  32937. // Base texture
  32938. newTexture.hasAlpha = this.hasAlpha;
  32939. newTexture.level = this.level;
  32940. // RenderTarget Texture
  32941. newTexture.coordinatesMode = this.coordinatesMode;
  32942. newTexture.renderList = this.renderList.slice(0);
  32943. return newTexture;
  32944. };
  32945. RenderTargetTexture.prototype.serialize = function () {
  32946. if (!this.name) {
  32947. return null;
  32948. }
  32949. var serializationObject = _super.prototype.serialize.call(this);
  32950. serializationObject.renderTargetSize = this.getRenderSize();
  32951. serializationObject.renderList = [];
  32952. for (var index = 0; index < this.renderList.length; index++) {
  32953. serializationObject.renderList.push(this.renderList[index].id);
  32954. }
  32955. return serializationObject;
  32956. };
  32957. RenderTargetTexture.prototype.dispose = function () {
  32958. if (this._postProcessManager) {
  32959. this._postProcessManager.dispose();
  32960. this._postProcessManager = null;
  32961. }
  32962. this.clearPostProcesses(true);
  32963. _super.prototype.dispose.call(this);
  32964. };
  32965. return RenderTargetTexture;
  32966. }(BABYLON.Texture));
  32967. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  32968. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  32969. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  32970. BABYLON.RenderTargetTexture = RenderTargetTexture;
  32971. })(BABYLON || (BABYLON = {}));
  32972. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  32973. var BABYLON;
  32974. (function (BABYLON) {
  32975. ;
  32976. var MultiRenderTarget = (function (_super) {
  32977. __extends(MultiRenderTarget, _super);
  32978. function MultiRenderTarget(name, size, count, scene, options) {
  32979. var _this = this;
  32980. options = options || {};
  32981. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  32982. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  32983. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  32984. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  32985. if (!_this.isSupported) {
  32986. _this.dispose();
  32987. return;
  32988. }
  32989. var types = [];
  32990. var samplingModes = [];
  32991. for (var i = 0; i < count; i++) {
  32992. if (options.types && options.types[i]) {
  32993. types.push(options.types[i]);
  32994. }
  32995. else {
  32996. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  32997. }
  32998. if (options.samplingModes && options.samplingModes[i]) {
  32999. samplingModes.push(options.samplingModes[i]);
  33000. }
  33001. else {
  33002. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33003. }
  33004. }
  33005. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  33006. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  33007. _this._count = count;
  33008. _this._size = size;
  33009. _this._multiRenderTargetOptions = {
  33010. samplingModes: samplingModes,
  33011. generateMipMaps: generateMipMaps,
  33012. generateDepthBuffer: generateDepthBuffer,
  33013. generateStencilBuffer: generateStencilBuffer,
  33014. generateDepthTexture: generateDepthTexture,
  33015. types: types,
  33016. textureCount: count
  33017. };
  33018. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  33019. _this._createInternalTextures();
  33020. return _this;
  33021. }
  33022. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33023. get: function () {
  33024. var engine = this.getScene().getEngine();
  33025. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33026. },
  33027. enumerable: true,
  33028. configurable: true
  33029. });
  33030. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33031. get: function () {
  33032. return this._textures;
  33033. },
  33034. enumerable: true,
  33035. configurable: true
  33036. });
  33037. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33038. get: function () {
  33039. return this._textures[this._textures.length - 1];
  33040. },
  33041. enumerable: true,
  33042. configurable: true
  33043. });
  33044. MultiRenderTarget.prototype._createInternalTextures = function () {
  33045. this._textures = [];
  33046. for (var i = 0; i < this._webGLTextures.length; i++) {
  33047. var texture = new BABYLON.Texture(null, this.getScene());
  33048. texture._texture = this._webGLTextures[i];
  33049. this._textures.push(texture);
  33050. }
  33051. // Keeps references to frame buffer and stencil/depth buffer
  33052. this._texture = this._webGLTextures[0];
  33053. };
  33054. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33055. get: function () {
  33056. return this._samples;
  33057. },
  33058. set: function (value) {
  33059. if (this._samples === value) {
  33060. return;
  33061. }
  33062. for (var i = 0; i < this._webGLTextures.length; i++) {
  33063. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  33064. }
  33065. },
  33066. enumerable: true,
  33067. configurable: true
  33068. });
  33069. MultiRenderTarget.prototype.resize = function (size) {
  33070. this.releaseInternalTextures();
  33071. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33072. this._createInternalTextures();
  33073. };
  33074. MultiRenderTarget.prototype.dispose = function () {
  33075. this.releaseInternalTextures();
  33076. _super.prototype.dispose.call(this);
  33077. };
  33078. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33079. if (!this._webGLTextures) {
  33080. return;
  33081. }
  33082. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  33083. if (this._webGLTextures[i] !== undefined) {
  33084. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  33085. this._webGLTextures.splice(i, 1);
  33086. }
  33087. }
  33088. };
  33089. return MultiRenderTarget;
  33090. }(BABYLON.RenderTargetTexture));
  33091. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33092. })(BABYLON || (BABYLON = {}));
  33093. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33094. /// <reference path="babylon.renderTargetTexture.ts" />
  33095. var BABYLON;
  33096. (function (BABYLON) {
  33097. var MirrorTexture = (function (_super) {
  33098. __extends(MirrorTexture, _super);
  33099. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33100. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33101. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33102. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33103. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33104. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33105. _this._transformMatrix = BABYLON.Matrix.Zero();
  33106. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33107. _this._blurKernelX = 0;
  33108. _this._blurKernelY = 0;
  33109. _this._blurRatio = 1.0;
  33110. _this.onBeforeRenderObservable.add(function () {
  33111. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33112. _this._savedViewMatrix = scene.getViewMatrix();
  33113. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33114. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33115. scene.clipPlane = _this.mirrorPlane;
  33116. scene.getEngine().cullBackFaces = false;
  33117. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  33118. });
  33119. _this.onAfterRenderObservable.add(function () {
  33120. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33121. scene.getEngine().cullBackFaces = true;
  33122. scene._mirroredCameraPosition = null;
  33123. delete scene.clipPlane;
  33124. });
  33125. return _this;
  33126. }
  33127. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33128. get: function () {
  33129. return this._blurRatio;
  33130. },
  33131. set: function (value) {
  33132. if (this._blurRatio === value) {
  33133. return;
  33134. }
  33135. this._blurRatio = value;
  33136. this._preparePostProcesses();
  33137. },
  33138. enumerable: true,
  33139. configurable: true
  33140. });
  33141. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33142. set: function (value) {
  33143. this.blurKernelX = value;
  33144. this.blurKernelY = value;
  33145. },
  33146. enumerable: true,
  33147. configurable: true
  33148. });
  33149. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  33150. get: function () {
  33151. return this._blurKernelX;
  33152. },
  33153. set: function (value) {
  33154. if (this._blurKernelX === value) {
  33155. return;
  33156. }
  33157. this._blurKernelX = value;
  33158. this._preparePostProcesses();
  33159. },
  33160. enumerable: true,
  33161. configurable: true
  33162. });
  33163. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  33164. get: function () {
  33165. return this._blurKernelY;
  33166. },
  33167. set: function (value) {
  33168. if (this._blurKernelY === value) {
  33169. return;
  33170. }
  33171. this._blurKernelY = value;
  33172. this._preparePostProcesses();
  33173. },
  33174. enumerable: true,
  33175. configurable: true
  33176. });
  33177. MirrorTexture.prototype._preparePostProcesses = function () {
  33178. this.clearPostProcesses(true);
  33179. if (this._blurKernelX && this._blurKernelY) {
  33180. var engine = this.getScene().getEngine();
  33181. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33182. 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);
  33183. this._blurX.autoClear = false;
  33184. if (this._blurRatio === 1) {
  33185. this._blurX.outputTexture = this._texture;
  33186. }
  33187. else {
  33188. this._blurX.alwaysForcePOT = true;
  33189. }
  33190. 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);
  33191. this._blurY.autoClear = false;
  33192. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  33193. this.addPostProcess(this._blurX);
  33194. this.addPostProcess(this._blurY);
  33195. }
  33196. };
  33197. MirrorTexture.prototype.clone = function () {
  33198. var textureSize = this.getSize();
  33199. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33200. // Base texture
  33201. newTexture.hasAlpha = this.hasAlpha;
  33202. newTexture.level = this.level;
  33203. // Mirror Texture
  33204. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33205. newTexture.renderList = this.renderList.slice(0);
  33206. return newTexture;
  33207. };
  33208. MirrorTexture.prototype.serialize = function () {
  33209. if (!this.name) {
  33210. return null;
  33211. }
  33212. var serializationObject = _super.prototype.serialize.call(this);
  33213. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33214. return serializationObject;
  33215. };
  33216. return MirrorTexture;
  33217. }(BABYLON.RenderTargetTexture));
  33218. BABYLON.MirrorTexture = MirrorTexture;
  33219. })(BABYLON || (BABYLON = {}));
  33220. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33221. /// <reference path="babylon.renderTargetTexture.ts" />
  33222. var BABYLON;
  33223. (function (BABYLON) {
  33224. /**
  33225. * Creates a refraction texture used by refraction channel of the standard material.
  33226. * @param name the texture name
  33227. * @param size size of the underlying texture
  33228. * @param scene root scene
  33229. */
  33230. var RefractionTexture = (function (_super) {
  33231. __extends(RefractionTexture, _super);
  33232. function RefractionTexture(name, size, scene, generateMipMaps) {
  33233. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33234. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33235. _this.depth = 2.0;
  33236. _this.onBeforeRenderObservable.add(function () {
  33237. scene.clipPlane = _this.refractionPlane;
  33238. });
  33239. _this.onAfterRenderObservable.add(function () {
  33240. delete scene.clipPlane;
  33241. });
  33242. return _this;
  33243. }
  33244. RefractionTexture.prototype.clone = function () {
  33245. var textureSize = this.getSize();
  33246. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33247. // Base texture
  33248. newTexture.hasAlpha = this.hasAlpha;
  33249. newTexture.level = this.level;
  33250. // Refraction Texture
  33251. newTexture.refractionPlane = this.refractionPlane.clone();
  33252. newTexture.renderList = this.renderList.slice(0);
  33253. newTexture.depth = this.depth;
  33254. return newTexture;
  33255. };
  33256. RefractionTexture.prototype.serialize = function () {
  33257. if (!this.name) {
  33258. return null;
  33259. }
  33260. var serializationObject = _super.prototype.serialize.call(this);
  33261. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33262. serializationObject.depth = this.depth;
  33263. return serializationObject;
  33264. };
  33265. return RefractionTexture;
  33266. }(BABYLON.RenderTargetTexture));
  33267. BABYLON.RefractionTexture = RefractionTexture;
  33268. })(BABYLON || (BABYLON = {}));
  33269. //# sourceMappingURL=babylon.refractionTexture.js.map
  33270. /// <reference path="babylon.texture.ts" />
  33271. var BABYLON;
  33272. (function (BABYLON) {
  33273. var DynamicTexture = (function (_super) {
  33274. __extends(DynamicTexture, _super);
  33275. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33277. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33278. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33279. _this.name = name;
  33280. var engine = _this.getScene().getEngine();
  33281. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33282. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33283. _this._generateMipMaps = generateMipMaps;
  33284. if (options.getContext) {
  33285. _this._canvas = options;
  33286. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33287. }
  33288. else {
  33289. _this._canvas = document.createElement("canvas");
  33290. if (options.width) {
  33291. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33292. }
  33293. else {
  33294. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33295. }
  33296. }
  33297. var textureSize = _this.getSize();
  33298. _this._canvas.width = textureSize.width;
  33299. _this._canvas.height = textureSize.height;
  33300. _this._context = _this._canvas.getContext("2d");
  33301. return _this;
  33302. }
  33303. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33304. get: function () {
  33305. return true;
  33306. },
  33307. enumerable: true,
  33308. configurable: true
  33309. });
  33310. DynamicTexture.prototype._recreate = function (textureSize) {
  33311. this._canvas.width = textureSize.width;
  33312. this._canvas.height = textureSize.height;
  33313. this.releaseInternalTexture();
  33314. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33315. };
  33316. DynamicTexture.prototype.scale = function (ratio) {
  33317. var textureSize = this.getSize();
  33318. textureSize.width *= ratio;
  33319. textureSize.height *= ratio;
  33320. this._recreate(textureSize);
  33321. };
  33322. DynamicTexture.prototype.scaleTo = function (width, height) {
  33323. var textureSize = this.getSize();
  33324. textureSize.width = width;
  33325. textureSize.height = height;
  33326. this._recreate(textureSize);
  33327. };
  33328. DynamicTexture.prototype.getContext = function () {
  33329. return this._context;
  33330. };
  33331. DynamicTexture.prototype.clear = function () {
  33332. var size = this.getSize();
  33333. this._context.fillRect(0, 0, size.width, size.height);
  33334. };
  33335. DynamicTexture.prototype.update = function (invertY) {
  33336. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33337. };
  33338. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33339. if (update === void 0) { update = true; }
  33340. var size = this.getSize();
  33341. if (clearColor) {
  33342. this._context.fillStyle = clearColor;
  33343. this._context.fillRect(0, 0, size.width, size.height);
  33344. }
  33345. this._context.font = font;
  33346. if (x === null || x === undefined) {
  33347. var textSize = this._context.measureText(text);
  33348. x = (size.width - textSize.width) / 2;
  33349. }
  33350. if (y === null || y === undefined) {
  33351. var fontSize = parseInt((font.replace(/\D/g, '')));
  33352. ;
  33353. y = (size.height / 2) + (fontSize / 3.65);
  33354. }
  33355. this._context.fillStyle = color;
  33356. this._context.fillText(text, x, y);
  33357. if (update) {
  33358. this.update(invertY);
  33359. }
  33360. };
  33361. DynamicTexture.prototype.clone = function () {
  33362. var textureSize = this.getSize();
  33363. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33364. // Base texture
  33365. newTexture.hasAlpha = this.hasAlpha;
  33366. newTexture.level = this.level;
  33367. // Dynamic Texture
  33368. newTexture.wrapU = this.wrapU;
  33369. newTexture.wrapV = this.wrapV;
  33370. return newTexture;
  33371. };
  33372. return DynamicTexture;
  33373. }(BABYLON.Texture));
  33374. BABYLON.DynamicTexture = DynamicTexture;
  33375. })(BABYLON || (BABYLON = {}));
  33376. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33377. var BABYLON;
  33378. (function (BABYLON) {
  33379. var VideoTexture = (function (_super) {
  33380. __extends(VideoTexture, _super);
  33381. /**
  33382. * Creates a video texture.
  33383. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33384. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33385. * @param {BABYLON.Scene} scene is obviously the current scene.
  33386. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33387. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33388. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33389. */
  33390. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33391. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33392. if (invertY === void 0) { invertY = false; }
  33393. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33394. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33395. _this._autoLaunch = true;
  33396. var urls;
  33397. _this.name = name;
  33398. if (urlsOrVideo instanceof HTMLVideoElement) {
  33399. _this.video = urlsOrVideo;
  33400. }
  33401. else {
  33402. urls = urlsOrVideo;
  33403. _this.video = document.createElement("video");
  33404. _this.video.autoplay = false;
  33405. _this.video.loop = true;
  33406. }
  33407. _this._generateMipMaps = generateMipMaps;
  33408. _this._samplingMode = samplingMode;
  33409. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  33410. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33411. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33412. }
  33413. else {
  33414. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33415. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33416. _this._generateMipMaps = false;
  33417. }
  33418. if (urls) {
  33419. _this.video.addEventListener("canplay", function () {
  33420. _this._createTexture();
  33421. });
  33422. urls.forEach(function (url) {
  33423. var source = document.createElement("source");
  33424. source.src = url;
  33425. _this.video.appendChild(source);
  33426. });
  33427. }
  33428. else {
  33429. _this._createTexture();
  33430. }
  33431. _this._lastUpdate = BABYLON.Tools.Now;
  33432. return _this;
  33433. }
  33434. VideoTexture.prototype.__setTextureReady = function () {
  33435. this._texture.isReady = true;
  33436. };
  33437. VideoTexture.prototype._createTexture = function () {
  33438. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33439. if (this._autoLaunch) {
  33440. this._autoLaunch = false;
  33441. this.video.play();
  33442. }
  33443. this._setTextureReady = this.__setTextureReady.bind(this);
  33444. this.video.addEventListener("playing", this._setTextureReady);
  33445. };
  33446. VideoTexture.prototype.update = function () {
  33447. var now = BABYLON.Tools.Now;
  33448. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  33449. return false;
  33450. }
  33451. this._lastUpdate = now;
  33452. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  33453. return true;
  33454. };
  33455. VideoTexture.prototype.dispose = function () {
  33456. _super.prototype.dispose.call(this);
  33457. this.video.removeEventListener("playing", this._setTextureReady);
  33458. };
  33459. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  33460. var video = document.createElement("video");
  33461. var constraintsDeviceId;
  33462. if (constraints && constraints.deviceId) {
  33463. constraintsDeviceId = {
  33464. exact: constraints.deviceId
  33465. };
  33466. }
  33467. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  33468. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  33469. if (navigator.getUserMedia) {
  33470. navigator.getUserMedia({
  33471. video: {
  33472. deviceId: constraintsDeviceId,
  33473. width: {
  33474. min: (constraints && constraints.minWidth) || 256,
  33475. max: (constraints && constraints.maxWidth) || 640
  33476. },
  33477. height: {
  33478. min: (constraints && constraints.minHeight) || 256,
  33479. max: (constraints && constraints.maxHeight) || 480
  33480. }
  33481. }
  33482. }, function (stream) {
  33483. if (video.mozSrcObject !== undefined) {
  33484. video.mozSrcObject = stream;
  33485. }
  33486. else {
  33487. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  33488. }
  33489. video.play();
  33490. if (onReady) {
  33491. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  33492. }
  33493. }, function (e) {
  33494. BABYLON.Tools.Error(e.name);
  33495. });
  33496. }
  33497. };
  33498. return VideoTexture;
  33499. }(BABYLON.Texture));
  33500. BABYLON.VideoTexture = VideoTexture;
  33501. })(BABYLON || (BABYLON = {}));
  33502. //# sourceMappingURL=babylon.videoTexture.js.map
  33503. var BABYLON;
  33504. (function (BABYLON) {
  33505. var RawTexture = (function (_super) {
  33506. __extends(RawTexture, _super);
  33507. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33509. if (invertY === void 0) { invertY = false; }
  33510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33511. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33512. _this.format = format;
  33513. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33514. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33515. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33516. return _this;
  33517. }
  33518. RawTexture.prototype.update = function (data) {
  33519. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33520. };
  33521. // Statics
  33522. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33523. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33524. if (invertY === void 0) { invertY = false; }
  33525. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33526. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33527. };
  33528. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33529. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33530. if (invertY === void 0) { invertY = false; }
  33531. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33532. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33533. };
  33534. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33535. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33536. if (invertY === void 0) { invertY = false; }
  33537. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33538. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33539. };
  33540. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33541. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33542. if (invertY === void 0) { invertY = false; }
  33543. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33544. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33545. };
  33546. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33547. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33548. if (invertY === void 0) { invertY = false; }
  33549. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33550. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33551. };
  33552. return RawTexture;
  33553. }(BABYLON.Texture));
  33554. BABYLON.RawTexture = RawTexture;
  33555. })(BABYLON || (BABYLON = {}));
  33556. //# sourceMappingURL=babylon.rawTexture.js.map
  33557. var BABYLON;
  33558. (function (BABYLON) {
  33559. var Internals;
  33560. (function (Internals) {
  33561. /*
  33562. * Based on jsTGALoader - Javascript loader for TGA file
  33563. * By Vincent Thibault
  33564. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  33565. */
  33566. var TGATools = (function () {
  33567. function TGATools() {
  33568. }
  33569. TGATools.GetTGAHeader = function (data) {
  33570. var offset = 0;
  33571. var header = {
  33572. id_length: data[offset++],
  33573. colormap_type: data[offset++],
  33574. image_type: data[offset++],
  33575. colormap_index: data[offset++] | data[offset++] << 8,
  33576. colormap_length: data[offset++] | data[offset++] << 8,
  33577. colormap_size: data[offset++],
  33578. origin: [
  33579. data[offset++] | data[offset++] << 8,
  33580. data[offset++] | data[offset++] << 8
  33581. ],
  33582. width: data[offset++] | data[offset++] << 8,
  33583. height: data[offset++] | data[offset++] << 8,
  33584. pixel_size: data[offset++],
  33585. flags: data[offset++]
  33586. };
  33587. return header;
  33588. };
  33589. TGATools.UploadContent = function (gl, data) {
  33590. // Not enough data to contain header ?
  33591. if (data.length < 19) {
  33592. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  33593. return;
  33594. }
  33595. // Read Header
  33596. var offset = 18;
  33597. var header = TGATools.GetTGAHeader(data);
  33598. // Assume it's a valid Targa file.
  33599. if (header.id_length + offset > data.length) {
  33600. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  33601. return;
  33602. }
  33603. // Skip not needed data
  33604. offset += header.id_length;
  33605. var use_rle = false;
  33606. var use_pal = false;
  33607. var use_rgb = false;
  33608. var use_grey = false;
  33609. // Get some informations.
  33610. switch (header.image_type) {
  33611. case TGATools._TYPE_RLE_INDEXED:
  33612. use_rle = true;
  33613. case TGATools._TYPE_INDEXED:
  33614. use_pal = true;
  33615. break;
  33616. case TGATools._TYPE_RLE_RGB:
  33617. use_rle = true;
  33618. case TGATools._TYPE_RGB:
  33619. use_rgb = true;
  33620. break;
  33621. case TGATools._TYPE_RLE_GREY:
  33622. use_rle = true;
  33623. case TGATools._TYPE_GREY:
  33624. use_grey = true;
  33625. break;
  33626. }
  33627. var pixel_data;
  33628. var numAlphaBits = header.flags & 0xf;
  33629. var pixel_size = header.pixel_size >> 3;
  33630. var pixel_total = header.width * header.height * pixel_size;
  33631. // Read palettes
  33632. var palettes;
  33633. if (use_pal) {
  33634. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  33635. }
  33636. // Read LRE
  33637. if (use_rle) {
  33638. pixel_data = new Uint8Array(pixel_total);
  33639. var c, count, i;
  33640. var localOffset = 0;
  33641. var pixels = new Uint8Array(pixel_size);
  33642. while (offset < pixel_total && localOffset < pixel_total) {
  33643. c = data[offset++];
  33644. count = (c & 0x7f) + 1;
  33645. // RLE pixels
  33646. if (c & 0x80) {
  33647. // Bind pixel tmp array
  33648. for (i = 0; i < pixel_size; ++i) {
  33649. pixels[i] = data[offset++];
  33650. }
  33651. // Copy pixel array
  33652. for (i = 0; i < count; ++i) {
  33653. pixel_data.set(pixels, localOffset + i * pixel_size);
  33654. }
  33655. localOffset += pixel_size * count;
  33656. }
  33657. else {
  33658. count *= pixel_size;
  33659. for (i = 0; i < count; ++i) {
  33660. pixel_data[localOffset + i] = data[offset++];
  33661. }
  33662. localOffset += count;
  33663. }
  33664. }
  33665. }
  33666. else {
  33667. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  33668. }
  33669. // Load to texture
  33670. var x_start, y_start, x_step, y_step, y_end, x_end;
  33671. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  33672. default:
  33673. case TGATools._ORIGIN_UL:
  33674. x_start = 0;
  33675. x_step = 1;
  33676. x_end = header.width;
  33677. y_start = 0;
  33678. y_step = 1;
  33679. y_end = header.height;
  33680. break;
  33681. case TGATools._ORIGIN_BL:
  33682. x_start = 0;
  33683. x_step = 1;
  33684. x_end = header.width;
  33685. y_start = header.height - 1;
  33686. y_step = -1;
  33687. y_end = -1;
  33688. break;
  33689. case TGATools._ORIGIN_UR:
  33690. x_start = header.width - 1;
  33691. x_step = -1;
  33692. x_end = -1;
  33693. y_start = 0;
  33694. y_step = 1;
  33695. y_end = header.height;
  33696. break;
  33697. case TGATools._ORIGIN_BR:
  33698. x_start = header.width - 1;
  33699. x_step = -1;
  33700. x_end = -1;
  33701. y_start = header.height - 1;
  33702. y_step = -1;
  33703. y_end = -1;
  33704. break;
  33705. }
  33706. // Load the specify method
  33707. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  33708. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  33709. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  33710. };
  33711. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33712. var image = pixel_data, colormap = palettes;
  33713. var width = header.width, height = header.height;
  33714. var color, i = 0, x, y;
  33715. var imageData = new Uint8Array(width * height * 4);
  33716. for (y = y_start; y !== y_end; y += y_step) {
  33717. for (x = x_start; x !== x_end; x += x_step, i++) {
  33718. color = image[i];
  33719. imageData[(x + width * y) * 4 + 3] = 255;
  33720. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  33721. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  33722. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  33723. }
  33724. }
  33725. return imageData;
  33726. };
  33727. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33728. var image = pixel_data;
  33729. var width = header.width, height = header.height;
  33730. var color, i = 0, x, y;
  33731. var imageData = new Uint8Array(width * height * 4);
  33732. for (y = y_start; y !== y_end; y += y_step) {
  33733. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33734. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  33735. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  33736. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  33737. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  33738. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  33739. }
  33740. }
  33741. return imageData;
  33742. };
  33743. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33744. var image = pixel_data;
  33745. var width = header.width, height = header.height;
  33746. var i = 0, x, y;
  33747. var imageData = new Uint8Array(width * height * 4);
  33748. for (y = y_start; y !== y_end; y += y_step) {
  33749. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  33750. imageData[(x + width * y) * 4 + 3] = 255;
  33751. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33752. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33753. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33754. }
  33755. }
  33756. return imageData;
  33757. };
  33758. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33759. var image = pixel_data;
  33760. var width = header.width, height = header.height;
  33761. var i = 0, x, y;
  33762. var imageData = new Uint8Array(width * height * 4);
  33763. for (y = y_start; y !== y_end; y += y_step) {
  33764. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  33765. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33766. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33767. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33768. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  33769. }
  33770. }
  33771. return imageData;
  33772. };
  33773. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33774. var image = pixel_data;
  33775. var width = header.width, height = header.height;
  33776. var color, i = 0, x, y;
  33777. var imageData = new Uint8Array(width * height * 4);
  33778. for (y = y_start; y !== y_end; y += y_step) {
  33779. for (x = x_start; x !== x_end; x += x_step, i++) {
  33780. color = image[i];
  33781. imageData[(x + width * y) * 4 + 0] = color;
  33782. imageData[(x + width * y) * 4 + 1] = color;
  33783. imageData[(x + width * y) * 4 + 2] = color;
  33784. imageData[(x + width * y) * 4 + 3] = 255;
  33785. }
  33786. }
  33787. return imageData;
  33788. };
  33789. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33790. var image = pixel_data;
  33791. var width = header.width, height = header.height;
  33792. var i = 0, x, y;
  33793. var imageData = new Uint8Array(width * height * 4);
  33794. for (y = y_start; y !== y_end; y += y_step) {
  33795. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33796. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  33797. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  33798. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33799. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  33800. }
  33801. }
  33802. return imageData;
  33803. };
  33804. return TGATools;
  33805. }());
  33806. TGATools._TYPE_NO_DATA = 0;
  33807. TGATools._TYPE_INDEXED = 1;
  33808. TGATools._TYPE_RGB = 2;
  33809. TGATools._TYPE_GREY = 3;
  33810. TGATools._TYPE_RLE_INDEXED = 9;
  33811. TGATools._TYPE_RLE_RGB = 10;
  33812. TGATools._TYPE_RLE_GREY = 11;
  33813. TGATools._ORIGIN_MASK = 0x30;
  33814. TGATools._ORIGIN_SHIFT = 0x04;
  33815. TGATools._ORIGIN_BL = 0x00;
  33816. TGATools._ORIGIN_BR = 0x01;
  33817. TGATools._ORIGIN_UL = 0x02;
  33818. TGATools._ORIGIN_UR = 0x03;
  33819. Internals.TGATools = TGATools;
  33820. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33821. })(BABYLON || (BABYLON = {}));
  33822. //# sourceMappingURL=babylon.tga.js.map
  33823. var BABYLON;
  33824. (function (BABYLON) {
  33825. var Internals;
  33826. (function (Internals) {
  33827. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  33828. // All values and structures referenced from:
  33829. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  33830. var DDS_MAGIC = 0x20534444;
  33831. 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;
  33832. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  33833. 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;
  33834. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  33835. function FourCCToInt32(value) {
  33836. return value.charCodeAt(0) +
  33837. (value.charCodeAt(1) << 8) +
  33838. (value.charCodeAt(2) << 16) +
  33839. (value.charCodeAt(3) << 24);
  33840. }
  33841. function Int32ToFourCC(value) {
  33842. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  33843. }
  33844. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  33845. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  33846. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  33847. var headerLengthInt = 31; // The header length in 32 bit ints
  33848. // Offsets into the header array
  33849. var off_magic = 0;
  33850. var off_size = 1;
  33851. var off_flags = 2;
  33852. var off_height = 3;
  33853. var off_width = 4;
  33854. var off_mipmapCount = 7;
  33855. var off_pfFlags = 20;
  33856. var off_pfFourCC = 21;
  33857. var off_RGBbpp = 22;
  33858. var off_RMask = 23;
  33859. var off_GMask = 24;
  33860. var off_BMask = 25;
  33861. var off_AMask = 26;
  33862. var off_caps1 = 27;
  33863. var off_caps2 = 28;
  33864. ;
  33865. var DDSTools = (function () {
  33866. function DDSTools() {
  33867. }
  33868. DDSTools.GetDDSInfo = function (arrayBuffer) {
  33869. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  33870. var mipmapCount = 1;
  33871. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  33872. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33873. }
  33874. return {
  33875. width: header[off_width],
  33876. height: header[off_height],
  33877. mipmapCount: mipmapCount,
  33878. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  33879. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  33880. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  33881. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  33882. };
  33883. };
  33884. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33885. var byteArray = new Uint8Array(dataLength);
  33886. var srcData = new Uint8Array(arrayBuffer);
  33887. var index = 0;
  33888. for (var y = height - 1; y >= 0; y--) {
  33889. for (var x = 0; x < width; x++) {
  33890. var srcPos = dataOffset + (x + y * width) * 4;
  33891. byteArray[index + 2] = srcData[srcPos];
  33892. byteArray[index + 1] = srcData[srcPos + 1];
  33893. byteArray[index] = srcData[srcPos + 2];
  33894. byteArray[index + 3] = srcData[srcPos + 3];
  33895. index += 4;
  33896. }
  33897. }
  33898. return byteArray;
  33899. };
  33900. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33901. var byteArray = new Uint8Array(dataLength);
  33902. var srcData = new Uint8Array(arrayBuffer);
  33903. var index = 0;
  33904. for (var y = height - 1; y >= 0; y--) {
  33905. for (var x = 0; x < width; x++) {
  33906. var srcPos = dataOffset + (x + y * width) * 3;
  33907. byteArray[index + 2] = srcData[srcPos];
  33908. byteArray[index + 1] = srcData[srcPos + 1];
  33909. byteArray[index] = srcData[srcPos + 2];
  33910. index += 3;
  33911. }
  33912. }
  33913. return byteArray;
  33914. };
  33915. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33916. var byteArray = new Uint8Array(dataLength);
  33917. var srcData = new Uint8Array(arrayBuffer);
  33918. var index = 0;
  33919. for (var y = height - 1; y >= 0; y--) {
  33920. for (var x = 0; x < width; x++) {
  33921. var srcPos = dataOffset + (x + y * width);
  33922. byteArray[index] = srcData[srcPos];
  33923. index++;
  33924. }
  33925. }
  33926. return byteArray;
  33927. };
  33928. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  33929. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  33930. if (header[off_magic] != DDS_MAGIC) {
  33931. BABYLON.Tools.Error("Invalid magic number in DDS header");
  33932. return;
  33933. }
  33934. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  33935. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  33936. return;
  33937. }
  33938. if (info.isFourCC) {
  33939. fourCC = header[off_pfFourCC];
  33940. switch (fourCC) {
  33941. case FOURCC_DXT1:
  33942. blockBytes = 8;
  33943. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33944. break;
  33945. case FOURCC_DXT3:
  33946. blockBytes = 16;
  33947. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33948. break;
  33949. case FOURCC_DXT5:
  33950. blockBytes = 16;
  33951. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  33952. break;
  33953. default:
  33954. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  33955. return;
  33956. }
  33957. }
  33958. mipmapCount = 1;
  33959. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33960. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33961. }
  33962. var bpp = header[off_RGBbpp];
  33963. for (var face = 0; face < faces; face++) {
  33964. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33965. width = header[off_width];
  33966. height = header[off_height];
  33967. dataOffset = header[off_size] + 4;
  33968. for (i = 0; i < mipmapCount; ++i) {
  33969. if (info.isRGB) {
  33970. if (bpp === 24) {
  33971. dataLength = width * height * 3;
  33972. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33973. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33974. }
  33975. else {
  33976. dataLength = width * height * 4;
  33977. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33978. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33979. }
  33980. }
  33981. else if (info.isLuminance) {
  33982. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33983. var unpaddedRowSize = width;
  33984. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33985. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33986. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33987. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33988. }
  33989. else {
  33990. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33991. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33992. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33993. }
  33994. dataOffset += dataLength;
  33995. width *= 0.5;
  33996. height *= 0.5;
  33997. width = Math.max(1.0, width);
  33998. height = Math.max(1.0, height);
  33999. }
  34000. }
  34001. };
  34002. return DDSTools;
  34003. }());
  34004. Internals.DDSTools = DDSTools;
  34005. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34006. })(BABYLON || (BABYLON = {}));
  34007. //# sourceMappingURL=babylon.dds.js.map
  34008. var BABYLON;
  34009. (function (BABYLON) {
  34010. var Internals;
  34011. (function (Internals) {
  34012. /**
  34013. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  34014. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  34015. */
  34016. var KhronosTextureContainer = (function () {
  34017. /**
  34018. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  34019. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  34020. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  34021. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  34022. */
  34023. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  34024. this.arrayBuffer = arrayBuffer;
  34025. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  34026. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  34027. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  34028. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  34029. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  34030. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  34031. BABYLON.Tools.Error("texture missing KTX identifier");
  34032. return;
  34033. }
  34034. // load the reset of the header in native 32 bit int
  34035. var header = new Int32Array(this.arrayBuffer, 12, 13);
  34036. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  34037. var oppositeEndianess = header[0] === 0x01020304;
  34038. // read all the header elements in order they exist in the file, without modification (sans endainness)
  34039. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  34040. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  34041. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  34042. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  34043. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  34044. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  34045. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  34046. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  34047. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  34048. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  34049. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34050. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34051. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34052. if (this.glType !== 0) {
  34053. BABYLON.Tools.Error("only compressed formats currently supported");
  34054. return;
  34055. }
  34056. else {
  34057. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34058. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34059. }
  34060. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34061. BABYLON.Tools.Error("only 2D textures currently supported");
  34062. return;
  34063. }
  34064. if (this.numberOfArrayElements !== 0) {
  34065. BABYLON.Tools.Error("texture arrays not currently supported");
  34066. return;
  34067. }
  34068. if (this.numberOfFaces !== facesExpected) {
  34069. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34070. return;
  34071. }
  34072. // we now have a completely validated file, so could use existence of loadType as success
  34073. // would need to make this more elaborate & adjust checks above to support more than one load type
  34074. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  34075. }
  34076. // not as fast hardware based, but will probably never need to use
  34077. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  34078. return ((val & 0xFF) << 24)
  34079. | ((val & 0xFF00) << 8)
  34080. | ((val >> 8) & 0xFF00)
  34081. | ((val >> 24) & 0xFF);
  34082. };
  34083. /**
  34084. * It is assumed that the texture has already been created & is currently bound
  34085. */
  34086. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  34087. switch (this.loadType) {
  34088. case KhronosTextureContainer.COMPRESSED_2D:
  34089. this._upload2DCompressedLevels(gl, loadMipmaps);
  34090. break;
  34091. case KhronosTextureContainer.TEX_2D:
  34092. case KhronosTextureContainer.COMPRESSED_3D:
  34093. case KhronosTextureContainer.TEX_3D:
  34094. }
  34095. };
  34096. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  34097. // initialize width & height for level 1
  34098. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  34099. var width = this.pixelWidth;
  34100. var height = this.pixelHeight;
  34101. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  34102. for (var level = 0; level < mipmapCount; level++) {
  34103. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  34104. for (var face = 0; face < this.numberOfFaces; face++) {
  34105. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34106. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  34107. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  34108. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  34109. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  34110. }
  34111. width = Math.max(1.0, width * 0.5);
  34112. height = Math.max(1.0, height * 0.5);
  34113. }
  34114. };
  34115. return KhronosTextureContainer;
  34116. }());
  34117. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  34118. // load types
  34119. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  34120. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  34121. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  34122. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  34123. Internals.KhronosTextureContainer = KhronosTextureContainer;
  34124. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34125. })(BABYLON || (BABYLON = {}));
  34126. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  34127. /// <reference path="babylon.mesh.ts" />
  34128. var BABYLON;
  34129. (function (BABYLON) {
  34130. var GroundMesh = (function (_super) {
  34131. __extends(GroundMesh, _super);
  34132. function GroundMesh(name, scene) {
  34133. var _this = _super.call(this, name, scene) || this;
  34134. _this.generateOctree = false;
  34135. _this._worldInverse = new BABYLON.Matrix();
  34136. return _this;
  34137. }
  34138. GroundMesh.prototype.getClassName = function () {
  34139. return "GroundMesh";
  34140. };
  34141. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34142. get: function () {
  34143. return Math.min(this._subdivisionsX, this._subdivisionsY);
  34144. },
  34145. enumerable: true,
  34146. configurable: true
  34147. });
  34148. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  34149. get: function () {
  34150. return this._subdivisionsX;
  34151. },
  34152. enumerable: true,
  34153. configurable: true
  34154. });
  34155. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  34156. get: function () {
  34157. return this._subdivisionsY;
  34158. },
  34159. enumerable: true,
  34160. configurable: true
  34161. });
  34162. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34163. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34164. this._subdivisionsX = chunksCount;
  34165. this._subdivisionsY = chunksCount;
  34166. this.subdivide(chunksCount);
  34167. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34168. };
  34169. /**
  34170. * Returns a height (y) value in the Worl system :
  34171. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34172. * Returns the ground y position if (x, z) are outside the ground surface.
  34173. */
  34174. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34175. var world = this.getWorldMatrix();
  34176. var invMat = BABYLON.Tmp.Matrix[5];
  34177. world.invertToRef(invMat);
  34178. var tmpVect = BABYLON.Tmp.Vector3[8];
  34179. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  34180. x = tmpVect.x;
  34181. z = tmpVect.z;
  34182. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34183. return this.position.y;
  34184. }
  34185. if (!this._heightQuads || this._heightQuads.length == 0) {
  34186. this._initHeightQuads();
  34187. this._computeHeightQuads();
  34188. }
  34189. var facet = this._getFacetAt(x, z);
  34190. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34191. // return y in the World system
  34192. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  34193. return tmpVect.y;
  34194. };
  34195. /**
  34196. * Returns a normalized vector (Vector3) orthogonal to the ground
  34197. * at the ground coordinates (x, z) expressed in the World system.
  34198. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  34199. */
  34200. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34201. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  34202. this.getNormalAtCoordinatesToRef(x, z, normal);
  34203. return normal;
  34204. };
  34205. /**
  34206. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34207. * at the ground coordinates (x, z) expressed in the World system.
  34208. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34209. * Returns the GroundMesh.
  34210. */
  34211. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34212. var world = this.getWorldMatrix();
  34213. var tmpMat = BABYLON.Tmp.Matrix[5];
  34214. world.invertToRef(tmpMat);
  34215. var tmpVect = BABYLON.Tmp.Vector3[8];
  34216. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  34217. x = tmpVect.x;
  34218. z = tmpVect.z;
  34219. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34220. return this;
  34221. }
  34222. if (!this._heightQuads || this._heightQuads.length == 0) {
  34223. this._initHeightQuads();
  34224. this._computeHeightQuads();
  34225. }
  34226. var facet = this._getFacetAt(x, z);
  34227. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  34228. return this;
  34229. };
  34230. /**
  34231. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34232. * if the ground has been updated.
  34233. * This can be used in the render loop.
  34234. * Returns the GroundMesh.
  34235. */
  34236. GroundMesh.prototype.updateCoordinateHeights = function () {
  34237. if (!this._heightQuads || this._heightQuads.length == 0) {
  34238. this._initHeightQuads();
  34239. }
  34240. this._computeHeightQuads();
  34241. return this;
  34242. };
  34243. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34244. GroundMesh.prototype._getFacetAt = function (x, z) {
  34245. // retrieve col and row from x, z coordinates in the ground local system
  34246. var subdivisionsX = this._subdivisionsX;
  34247. var subdivisionsY = this._subdivisionsY;
  34248. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  34249. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  34250. var quad = this._heightQuads[row * this._subdivisionsX + col];
  34251. var facet;
  34252. if (z < quad.slope.x * x + quad.slope.y) {
  34253. facet = quad.facet1;
  34254. }
  34255. else {
  34256. facet = quad.facet2;
  34257. }
  34258. return facet;
  34259. };
  34260. // Creates and populates the heightMap array with "facet" elements :
  34261. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34262. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34263. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34264. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34265. // Returns the GroundMesh.
  34266. GroundMesh.prototype._initHeightQuads = function () {
  34267. var subdivisionsX = this._subdivisionsX;
  34268. var subdivisionsY = this._subdivisionsY;
  34269. this._heightQuads = new Array();
  34270. for (var row = 0; row < subdivisionsY; row++) {
  34271. for (var col = 0; col < subdivisionsX; col++) {
  34272. 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) };
  34273. this._heightQuads[row * subdivisionsX + col] = quad;
  34274. }
  34275. }
  34276. return this;
  34277. };
  34278. // Compute each quad element values and update the the heightMap array :
  34279. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34280. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34281. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34282. // Returns the GroundMesh.
  34283. GroundMesh.prototype._computeHeightQuads = function () {
  34284. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34285. var v1 = BABYLON.Tmp.Vector3[3];
  34286. var v2 = BABYLON.Tmp.Vector3[2];
  34287. var v3 = BABYLON.Tmp.Vector3[1];
  34288. var v4 = BABYLON.Tmp.Vector3[0];
  34289. var v1v2 = BABYLON.Tmp.Vector3[4];
  34290. var v1v3 = BABYLON.Tmp.Vector3[5];
  34291. var v1v4 = BABYLON.Tmp.Vector3[6];
  34292. var norm1 = BABYLON.Tmp.Vector3[7];
  34293. var norm2 = BABYLON.Tmp.Vector3[8];
  34294. var i = 0;
  34295. var j = 0;
  34296. var k = 0;
  34297. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34298. var h = 0;
  34299. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34300. var d2 = 0;
  34301. var subdivisionsX = this._subdivisionsX;
  34302. var subdivisionsY = this._subdivisionsY;
  34303. for (var row = 0; row < subdivisionsY; row++) {
  34304. for (var col = 0; col < subdivisionsX; col++) {
  34305. i = col * 3;
  34306. j = row * (subdivisionsX + 1) * 3;
  34307. k = (row + 1) * (subdivisionsX + 1) * 3;
  34308. v1.x = positions[j + i];
  34309. v1.y = positions[j + i + 1];
  34310. v1.z = positions[j + i + 2];
  34311. v2.x = positions[j + i + 3];
  34312. v2.y = positions[j + i + 4];
  34313. v2.z = positions[j + i + 5];
  34314. v3.x = positions[k + i];
  34315. v3.y = positions[k + i + 1];
  34316. v3.z = positions[k + i + 2];
  34317. v4.x = positions[k + i + 3];
  34318. v4.y = positions[k + i + 4];
  34319. v4.z = positions[k + i + 5];
  34320. // 2D slope V1V4
  34321. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34322. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34323. // facet equations :
  34324. // we compute each facet normal vector
  34325. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34326. // we compute the value d by applying the equation to v1 which belongs to the plane
  34327. // then we store the facet equation in a Vector4
  34328. v2.subtractToRef(v1, v1v2);
  34329. v3.subtractToRef(v1, v1v3);
  34330. v4.subtractToRef(v1, v1v4);
  34331. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34332. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34333. norm1.normalize();
  34334. norm2.normalize();
  34335. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34336. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34337. var quad = this._heightQuads[row * subdivisionsX + col];
  34338. quad.slope.copyFromFloats(cd, h);
  34339. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34340. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34341. }
  34342. }
  34343. return this;
  34344. };
  34345. GroundMesh.prototype.serialize = function (serializationObject) {
  34346. _super.prototype.serialize.call(this, serializationObject);
  34347. serializationObject.subdivisionsX = this._subdivisionsX;
  34348. serializationObject.subdivisionsY = this._subdivisionsY;
  34349. serializationObject.minX = this._minX;
  34350. serializationObject.maxX = this._maxX;
  34351. serializationObject.minZ = this._minZ;
  34352. serializationObject.maxZ = this._maxZ;
  34353. serializationObject.width = this._width;
  34354. serializationObject.height = this._height;
  34355. };
  34356. GroundMesh.Parse = function (parsedMesh, scene) {
  34357. var result = new GroundMesh(parsedMesh.name, scene);
  34358. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  34359. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  34360. result._minX = parsedMesh.minX;
  34361. result._maxX = parsedMesh.maxX;
  34362. result._minZ = parsedMesh.minZ;
  34363. result._maxZ = parsedMesh.maxZ;
  34364. result._width = parsedMesh.width;
  34365. result._height = parsedMesh.height;
  34366. return result;
  34367. };
  34368. return GroundMesh;
  34369. }(BABYLON.Mesh));
  34370. BABYLON.GroundMesh = GroundMesh;
  34371. })(BABYLON || (BABYLON = {}));
  34372. //# sourceMappingURL=babylon.groundMesh.js.map
  34373. var BABYLON;
  34374. (function (BABYLON) {
  34375. /**
  34376. * Creates an instance based on a source mesh.
  34377. */
  34378. var InstancedMesh = (function (_super) {
  34379. __extends(InstancedMesh, _super);
  34380. function InstancedMesh(name, source) {
  34381. var _this = _super.call(this, name, source.getScene()) || this;
  34382. source.instances.push(_this);
  34383. _this._sourceMesh = source;
  34384. _this.position.copyFrom(source.position);
  34385. _this.rotation.copyFrom(source.rotation);
  34386. _this.scaling.copyFrom(source.scaling);
  34387. if (source.rotationQuaternion) {
  34388. _this.rotationQuaternion = source.rotationQuaternion.clone();
  34389. }
  34390. _this.infiniteDistance = source.infiniteDistance;
  34391. _this.setPivotMatrix(source.getPivotMatrix());
  34392. _this.refreshBoundingInfo();
  34393. _this._syncSubMeshes();
  34394. return _this;
  34395. }
  34396. /**
  34397. * Returns the string "InstancedMesh".
  34398. */
  34399. InstancedMesh.prototype.getClassName = function () {
  34400. return "InstancedMesh";
  34401. };
  34402. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  34403. // Methods
  34404. get: function () {
  34405. return this._sourceMesh.receiveShadows;
  34406. },
  34407. enumerable: true,
  34408. configurable: true
  34409. });
  34410. Object.defineProperty(InstancedMesh.prototype, "material", {
  34411. get: function () {
  34412. return this._sourceMesh.material;
  34413. },
  34414. enumerable: true,
  34415. configurable: true
  34416. });
  34417. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  34418. get: function () {
  34419. return this._sourceMesh.visibility;
  34420. },
  34421. enumerable: true,
  34422. configurable: true
  34423. });
  34424. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  34425. get: function () {
  34426. return this._sourceMesh.skeleton;
  34427. },
  34428. enumerable: true,
  34429. configurable: true
  34430. });
  34431. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  34432. get: function () {
  34433. return this._sourceMesh.renderingGroupId;
  34434. },
  34435. enumerable: true,
  34436. configurable: true
  34437. });
  34438. /**
  34439. * Returns the total number of vertices (integer).
  34440. */
  34441. InstancedMesh.prototype.getTotalVertices = function () {
  34442. return this._sourceMesh.getTotalVertices();
  34443. };
  34444. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  34445. get: function () {
  34446. return this._sourceMesh;
  34447. },
  34448. enumerable: true,
  34449. configurable: true
  34450. });
  34451. /**
  34452. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  34453. */
  34454. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  34455. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  34456. };
  34457. /**
  34458. * Sets the vertex data of the mesh geometry for the requested `kind`.
  34459. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  34460. * The `data` are either a numeric array either a Float32Array.
  34461. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  34462. * 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).
  34463. * Note that a new underlying VertexBuffer object is created each call.
  34464. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  34465. *
  34466. * Possible `kind` values :
  34467. * - BABYLON.VertexBuffer.PositionKind
  34468. * - BABYLON.VertexBuffer.UVKind
  34469. * - BABYLON.VertexBuffer.UV2Kind
  34470. * - BABYLON.VertexBuffer.UV3Kind
  34471. * - BABYLON.VertexBuffer.UV4Kind
  34472. * - BABYLON.VertexBuffer.UV5Kind
  34473. * - BABYLON.VertexBuffer.UV6Kind
  34474. * - BABYLON.VertexBuffer.ColorKind
  34475. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34476. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34477. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34478. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34479. *
  34480. * Returns the Mesh.
  34481. */
  34482. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34483. if (this.sourceMesh) {
  34484. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  34485. }
  34486. return this.sourceMesh;
  34487. };
  34488. /**
  34489. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  34490. * If the mesh has no geometry, it is simply returned as it is.
  34491. * The `data` are either a numeric array either a Float32Array.
  34492. * No new underlying VertexBuffer object is created.
  34493. * 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.
  34494. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  34495. *
  34496. * Possible `kind` values :
  34497. * - BABYLON.VertexBuffer.PositionKind
  34498. * - BABYLON.VertexBuffer.UVKind
  34499. * - BABYLON.VertexBuffer.UV2Kind
  34500. * - BABYLON.VertexBuffer.UV3Kind
  34501. * - BABYLON.VertexBuffer.UV4Kind
  34502. * - BABYLON.VertexBuffer.UV5Kind
  34503. * - BABYLON.VertexBuffer.UV6Kind
  34504. * - BABYLON.VertexBuffer.ColorKind
  34505. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34506. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34507. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34508. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34509. *
  34510. * Returns the Mesh.
  34511. */
  34512. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  34513. if (this.sourceMesh) {
  34514. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  34515. }
  34516. return this.sourceMesh;
  34517. };
  34518. /**
  34519. * Sets the mesh indices.
  34520. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  34521. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  34522. * This method creates a new index buffer each call.
  34523. * Returns the Mesh.
  34524. */
  34525. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  34526. if (this.sourceMesh) {
  34527. this.sourceMesh.setIndices(indices, totalVertices);
  34528. }
  34529. return this.sourceMesh;
  34530. };
  34531. /**
  34532. * Boolean : True if the mesh owns the requested kind of data.
  34533. */
  34534. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  34535. return this._sourceMesh.isVerticesDataPresent(kind);
  34536. };
  34537. /**
  34538. * Returns an array of indices (IndicesArray).
  34539. */
  34540. InstancedMesh.prototype.getIndices = function () {
  34541. return this._sourceMesh.getIndices();
  34542. };
  34543. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  34544. get: function () {
  34545. return this._sourceMesh._positions;
  34546. },
  34547. enumerable: true,
  34548. configurable: true
  34549. });
  34550. /**
  34551. * Sets a new updated BoundingInfo to the mesh.
  34552. * Returns the mesh.
  34553. */
  34554. InstancedMesh.prototype.refreshBoundingInfo = function () {
  34555. var meshBB = this._sourceMesh.getBoundingInfo();
  34556. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  34557. this._updateBoundingInfo();
  34558. return this;
  34559. };
  34560. InstancedMesh.prototype._preActivate = function () {
  34561. if (this._currentLOD) {
  34562. this._currentLOD._preActivate();
  34563. }
  34564. return this;
  34565. };
  34566. InstancedMesh.prototype._activate = function (renderId) {
  34567. if (this._currentLOD) {
  34568. this._currentLOD._registerInstanceForRenderId(this, renderId);
  34569. }
  34570. return this;
  34571. };
  34572. /**
  34573. * Returns the current associated LOD AbstractMesh.
  34574. */
  34575. InstancedMesh.prototype.getLOD = function (camera) {
  34576. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  34577. if (this._currentLOD === this.sourceMesh) {
  34578. return this;
  34579. }
  34580. return this._currentLOD;
  34581. };
  34582. InstancedMesh.prototype._syncSubMeshes = function () {
  34583. this.releaseSubMeshes();
  34584. if (this._sourceMesh.subMeshes) {
  34585. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  34586. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  34587. }
  34588. }
  34589. return this;
  34590. };
  34591. InstancedMesh.prototype._generatePointsArray = function () {
  34592. return this._sourceMesh._generatePointsArray();
  34593. };
  34594. /**
  34595. * Creates a new InstancedMesh from the current mesh.
  34596. * - name (string) : the cloned mesh name
  34597. * - newParent (optional Node) : the optional Node to parent the clone to.
  34598. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  34599. *
  34600. * Returns the clone.
  34601. */
  34602. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34603. var result = this._sourceMesh.createInstance(name);
  34604. // Deep copy
  34605. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  34606. // Bounding info
  34607. this.refreshBoundingInfo();
  34608. // Parent
  34609. if (newParent) {
  34610. result.parent = newParent;
  34611. }
  34612. if (!doNotCloneChildren) {
  34613. // Children
  34614. for (var index = 0; index < this.getScene().meshes.length; index++) {
  34615. var mesh = this.getScene().meshes[index];
  34616. if (mesh.parent === this) {
  34617. mesh.clone(mesh.name, result);
  34618. }
  34619. }
  34620. }
  34621. result.computeWorldMatrix(true);
  34622. return result;
  34623. };
  34624. /**
  34625. * Disposes the InstancedMesh.
  34626. * Returns nothing.
  34627. */
  34628. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  34629. // Remove from mesh
  34630. var index = this._sourceMesh.instances.indexOf(this);
  34631. this._sourceMesh.instances.splice(index, 1);
  34632. _super.prototype.dispose.call(this, doNotRecurse);
  34633. };
  34634. return InstancedMesh;
  34635. }(BABYLON.AbstractMesh));
  34636. BABYLON.InstancedMesh = InstancedMesh;
  34637. })(BABYLON || (BABYLON = {}));
  34638. //# sourceMappingURL=babylon.instancedMesh.js.map
  34639. /// <reference path="babylon.mesh.ts" />
  34640. var BABYLON;
  34641. (function (BABYLON) {
  34642. var LinesMesh = (function (_super) {
  34643. __extends(LinesMesh, _super);
  34644. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  34645. if (parent === void 0) { parent = null; }
  34646. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  34647. _this.useVertexColor = useVertexColor;
  34648. _this.color = new BABYLON.Color3(1, 1, 1);
  34649. _this.alpha = 1;
  34650. if (source) {
  34651. _this.color = source.color.clone();
  34652. _this.alpha = source.alpha;
  34653. _this.useVertexColor = source.useVertexColor;
  34654. }
  34655. _this._intersectionThreshold = 0.1;
  34656. var options = {
  34657. attributes: [BABYLON.VertexBuffer.PositionKind],
  34658. uniforms: ["world", "viewProjection"],
  34659. needAlphaBlending: false,
  34660. };
  34661. if (!useVertexColor) {
  34662. options.uniforms.push("color");
  34663. options.needAlphaBlending = true;
  34664. }
  34665. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  34666. return _this;
  34667. }
  34668. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34669. /**
  34670. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34671. * This margin is expressed in world space coordinates, so its value may vary.
  34672. * Default value is 0.1
  34673. * @returns the intersection Threshold value.
  34674. */
  34675. get: function () {
  34676. return this._intersectionThreshold;
  34677. },
  34678. /**
  34679. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34680. * This margin is expressed in world space coordinates, so its value may vary.
  34681. * @param value the new threshold to apply
  34682. */
  34683. set: function (value) {
  34684. if (this._intersectionThreshold === value) {
  34685. return;
  34686. }
  34687. this._intersectionThreshold = value;
  34688. if (this.geometry) {
  34689. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34690. }
  34691. },
  34692. enumerable: true,
  34693. configurable: true
  34694. });
  34695. /**
  34696. * Returns the string "LineMesh"
  34697. */
  34698. LinesMesh.prototype.getClassName = function () {
  34699. return "LinesMesh";
  34700. };
  34701. Object.defineProperty(LinesMesh.prototype, "material", {
  34702. get: function () {
  34703. return this._colorShader;
  34704. },
  34705. enumerable: true,
  34706. configurable: true
  34707. });
  34708. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34709. get: function () {
  34710. return false;
  34711. },
  34712. enumerable: true,
  34713. configurable: true
  34714. });
  34715. LinesMesh.prototype.createInstance = function (name) {
  34716. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34717. return null;
  34718. };
  34719. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34720. // VBOs
  34721. this._geometry._bind(this._colorShader.getEffect());
  34722. // Color
  34723. if (!this.useVertexColor) {
  34724. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34725. }
  34726. return this;
  34727. };
  34728. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34729. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34730. return this;
  34731. }
  34732. var engine = this.getScene().getEngine();
  34733. // Draw order
  34734. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34735. return this;
  34736. };
  34737. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34738. this._colorShader.dispose();
  34739. _super.prototype.dispose.call(this, doNotRecurse);
  34740. };
  34741. /**
  34742. * Returns a new LineMesh object cloned from the current one.
  34743. */
  34744. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34745. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34746. };
  34747. return LinesMesh;
  34748. }(BABYLON.Mesh));
  34749. BABYLON.LinesMesh = LinesMesh;
  34750. })(BABYLON || (BABYLON = {}));
  34751. //# sourceMappingURL=babylon.linesMesh.js.map
  34752. var BABYLON;
  34753. (function (BABYLON) {
  34754. var StandardMaterialDefines = (function (_super) {
  34755. __extends(StandardMaterialDefines, _super);
  34756. function StandardMaterialDefines() {
  34757. var _this = _super.call(this) || this;
  34758. _this.DIFFUSE = false;
  34759. _this.AMBIENT = false;
  34760. _this.OPACITY = false;
  34761. _this.OPACITYRGB = false;
  34762. _this.REFLECTION = false;
  34763. _this.EMISSIVE = false;
  34764. _this.SPECULAR = false;
  34765. _this.BUMP = false;
  34766. _this.PARALLAX = false;
  34767. _this.PARALLAXOCCLUSION = false;
  34768. _this.SPECULAROVERALPHA = false;
  34769. _this.CLIPPLANE = false;
  34770. _this.ALPHATEST = false;
  34771. _this.ALPHAFROMDIFFUSE = false;
  34772. _this.POINTSIZE = false;
  34773. _this.FOG = false;
  34774. _this.SPECULARTERM = false;
  34775. _this.DIFFUSEFRESNEL = false;
  34776. _this.OPACITYFRESNEL = false;
  34777. _this.REFLECTIONFRESNEL = false;
  34778. _this.REFRACTIONFRESNEL = false;
  34779. _this.EMISSIVEFRESNEL = false;
  34780. _this.FRESNEL = false;
  34781. _this.NORMAL = false;
  34782. _this.UV1 = false;
  34783. _this.UV2 = false;
  34784. _this.VERTEXCOLOR = false;
  34785. _this.VERTEXALPHA = false;
  34786. _this.NUM_BONE_INFLUENCERS = 0;
  34787. _this.BonesPerMesh = 0;
  34788. _this.INSTANCES = false;
  34789. _this.GLOSSINESS = false;
  34790. _this.ROUGHNESS = false;
  34791. _this.EMISSIVEASILLUMINATION = false;
  34792. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34793. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34794. _this.LIGHTMAP = false;
  34795. _this.USELIGHTMAPASSHADOWMAP = false;
  34796. _this.REFLECTIONMAP_3D = false;
  34797. _this.REFLECTIONMAP_SPHERICAL = false;
  34798. _this.REFLECTIONMAP_PLANAR = false;
  34799. _this.REFLECTIONMAP_CUBIC = false;
  34800. _this.REFLECTIONMAP_PROJECTION = false;
  34801. _this.REFLECTIONMAP_SKYBOX = false;
  34802. _this.REFLECTIONMAP_EXPLICIT = false;
  34803. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34804. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34805. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34806. _this.INVERTCUBICMAP = false;
  34807. _this.LOGARITHMICDEPTH = false;
  34808. _this.REFRACTION = false;
  34809. _this.REFRACTIONMAP_3D = false;
  34810. _this.REFLECTIONOVERALPHA = false;
  34811. _this.INVERTNORMALMAPX = false;
  34812. _this.INVERTNORMALMAPY = false;
  34813. _this.TWOSIDEDLIGHTING = false;
  34814. _this.SHADOWFLOAT = false;
  34815. _this.CAMERACOLORGRADING = false;
  34816. _this.CAMERACOLORCURVES = false;
  34817. _this.MORPHTARGETS = false;
  34818. _this.MORPHTARGETS_NORMAL = false;
  34819. _this.MORPHTARGETS_TANGENT = false;
  34820. _this.NUM_MORPH_INFLUENCERS = 0;
  34821. _this.USERIGHTHANDEDSYSTEM = false;
  34822. _this.rebuild();
  34823. return _this;
  34824. }
  34825. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34826. var modes = [
  34827. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34828. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34829. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34830. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34831. ];
  34832. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34833. var mode = modes_1[_i];
  34834. this[mode] = (mode === modeToEnable);
  34835. }
  34836. };
  34837. return StandardMaterialDefines;
  34838. }(BABYLON.MaterialDefines));
  34839. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34840. var StandardMaterial = (function (_super) {
  34841. __extends(StandardMaterial, _super);
  34842. function StandardMaterial(name, scene) {
  34843. var _this = _super.call(this, name, scene) || this;
  34844. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34845. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34846. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34847. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34848. _this.specularPower = 64;
  34849. _this._useAlphaFromDiffuseTexture = false;
  34850. _this._useEmissiveAsIllumination = false;
  34851. _this._linkEmissiveWithDiffuse = false;
  34852. _this._useSpecularOverAlpha = false;
  34853. _this._useReflectionOverAlpha = false;
  34854. _this._disableLighting = false;
  34855. _this._useParallax = false;
  34856. _this._useParallaxOcclusion = false;
  34857. _this.parallaxScaleBias = 0.05;
  34858. _this._roughness = 0;
  34859. _this.indexOfRefraction = 0.98;
  34860. _this.invertRefractionY = true;
  34861. _this._useLightmapAsShadowmap = false;
  34862. _this._useReflectionFresnelFromSpecular = false;
  34863. _this._useGlossinessFromSpecularMapAlpha = false;
  34864. _this._maxSimultaneousLights = 4;
  34865. /**
  34866. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34867. */
  34868. _this._invertNormalMapX = false;
  34869. /**
  34870. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34871. */
  34872. _this._invertNormalMapY = false;
  34873. /**
  34874. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34875. */
  34876. _this._twoSidedLighting = false;
  34877. /**
  34878. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34879. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34880. * 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;
  34881. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34882. */
  34883. _this._cameraColorCurves = null;
  34884. _this._renderTargets = new BABYLON.SmartArray(16);
  34885. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34886. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34887. _this.getRenderTargetTextures = function () {
  34888. _this._renderTargets.reset();
  34889. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34890. _this._renderTargets.push(_this._reflectionTexture);
  34891. }
  34892. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34893. _this._renderTargets.push(_this._refractionTexture);
  34894. }
  34895. return _this._renderTargets;
  34896. };
  34897. return _this;
  34898. }
  34899. StandardMaterial.prototype.getClassName = function () {
  34900. return "StandardMaterial";
  34901. };
  34902. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34903. get: function () {
  34904. return this._useLogarithmicDepth;
  34905. },
  34906. set: function (value) {
  34907. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34908. this._markAllSubMeshesAsMiscDirty();
  34909. },
  34910. enumerable: true,
  34911. configurable: true
  34912. });
  34913. StandardMaterial.prototype.needAlphaBlending = function () {
  34914. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34915. };
  34916. StandardMaterial.prototype.needAlphaTesting = function () {
  34917. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34918. };
  34919. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34920. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34921. };
  34922. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34923. return this._diffuseTexture;
  34924. };
  34925. /**
  34926. * Child classes can use it to update shaders
  34927. */
  34928. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34929. if (this.isFrozen) {
  34930. if (this._wasPreviouslyReady && subMesh.effect) {
  34931. return true;
  34932. }
  34933. }
  34934. if (!subMesh._materialDefines) {
  34935. subMesh._materialDefines = new StandardMaterialDefines();
  34936. }
  34937. var scene = this.getScene();
  34938. var defines = subMesh._materialDefines;
  34939. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34940. if (defines._renderId === scene.getRenderId()) {
  34941. return true;
  34942. }
  34943. }
  34944. var engine = scene.getEngine();
  34945. // Lights
  34946. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34947. // Textures
  34948. if (defines._areTexturesDirty) {
  34949. defines._needUVs = false;
  34950. if (scene.texturesEnabled) {
  34951. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34952. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34953. return false;
  34954. }
  34955. else {
  34956. defines._needUVs = true;
  34957. defines.DIFFUSE = true;
  34958. }
  34959. }
  34960. else {
  34961. defines.DIFFUSE = false;
  34962. }
  34963. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34964. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34965. return false;
  34966. }
  34967. else {
  34968. defines._needUVs = true;
  34969. defines.AMBIENT = true;
  34970. }
  34971. }
  34972. else {
  34973. defines.AMBIENT = false;
  34974. }
  34975. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34976. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34977. return false;
  34978. }
  34979. else {
  34980. defines._needUVs = true;
  34981. defines.OPACITY = true;
  34982. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34983. }
  34984. }
  34985. else {
  34986. defines.OPACITY = false;
  34987. }
  34988. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34989. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34990. return false;
  34991. }
  34992. else {
  34993. defines._needNormals = true;
  34994. defines.REFLECTION = true;
  34995. defines.ROUGHNESS = (this._roughness > 0);
  34996. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34997. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34998. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34999. switch (this._reflectionTexture.coordinatesMode) {
  35000. case BABYLON.Texture.CUBIC_MODE:
  35001. case BABYLON.Texture.INVCUBIC_MODE:
  35002. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35003. break;
  35004. case BABYLON.Texture.EXPLICIT_MODE:
  35005. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35006. break;
  35007. case BABYLON.Texture.PLANAR_MODE:
  35008. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35009. break;
  35010. case BABYLON.Texture.PROJECTION_MODE:
  35011. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35012. break;
  35013. case BABYLON.Texture.SKYBOX_MODE:
  35014. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35015. break;
  35016. case BABYLON.Texture.SPHERICAL_MODE:
  35017. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35018. break;
  35019. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35020. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35021. break;
  35022. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35023. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35024. break;
  35025. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35026. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35027. break;
  35028. }
  35029. }
  35030. }
  35031. else {
  35032. defines.REFLECTION = false;
  35033. }
  35034. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35035. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35036. return false;
  35037. }
  35038. else {
  35039. defines._needUVs = true;
  35040. defines.EMISSIVE = true;
  35041. }
  35042. }
  35043. else {
  35044. defines.EMISSIVE = false;
  35045. }
  35046. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35047. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35048. return false;
  35049. }
  35050. else {
  35051. defines._needUVs = true;
  35052. defines.LIGHTMAP = true;
  35053. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35054. }
  35055. }
  35056. else {
  35057. defines.LIGHTMAP = false;
  35058. }
  35059. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35060. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35061. return false;
  35062. }
  35063. else {
  35064. defines._needUVs = true;
  35065. defines.SPECULAR = true;
  35066. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35067. }
  35068. }
  35069. else {
  35070. defines.SPECULAR = false;
  35071. }
  35072. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35073. // Bump texure can not be not blocking.
  35074. if (!this._bumpTexture.isReady()) {
  35075. return false;
  35076. }
  35077. else {
  35078. defines._needUVs = true;
  35079. defines.BUMP = true;
  35080. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  35081. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  35082. defines.PARALLAX = this._useParallax;
  35083. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35084. }
  35085. }
  35086. else {
  35087. defines.BUMP = false;
  35088. }
  35089. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35090. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35091. return false;
  35092. }
  35093. else {
  35094. defines._needUVs = true;
  35095. defines.REFRACTION = true;
  35096. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35097. }
  35098. }
  35099. else {
  35100. defines.REFRACTION = false;
  35101. }
  35102. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  35103. // Camera Color Grading can not be none blocking.
  35104. if (!this._cameraColorGradingTexture.isReady()) {
  35105. return false;
  35106. }
  35107. else {
  35108. defines.CAMERACOLORGRADING = true;
  35109. }
  35110. }
  35111. else {
  35112. defines.CAMERACOLORGRADING = false;
  35113. }
  35114. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35115. }
  35116. else {
  35117. defines.DIFFUSE = false;
  35118. defines.AMBIENT = false;
  35119. defines.OPACITY = false;
  35120. defines.REFLECTION = false;
  35121. defines.EMISSIVE = false;
  35122. defines.LIGHTMAP = false;
  35123. defines.BUMP = false;
  35124. defines.REFRACTION = false;
  35125. defines.CAMERACOLORGRADING = false;
  35126. }
  35127. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  35128. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35129. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35130. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35131. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35132. }
  35133. if (defines._areFresnelDirty) {
  35134. if (StandardMaterial.FresnelEnabled) {
  35135. // Fresnel
  35136. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35137. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35138. this._reflectionFresnelParameters) {
  35139. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35140. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35141. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35142. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35143. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35144. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35145. defines._needNormals = true;
  35146. defines.FRESNEL = true;
  35147. }
  35148. }
  35149. else {
  35150. defines.FRESNEL = false;
  35151. }
  35152. }
  35153. // Misc.
  35154. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35155. // Attribs
  35156. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35157. // Values that need to be evaluated on every frame
  35158. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35159. if (scene._mirroredCameraPosition && defines.BUMP) {
  35160. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  35161. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  35162. defines.markAsUnprocessed();
  35163. }
  35164. // Get correct effect
  35165. if (defines.isDirty) {
  35166. defines.markAsProcessed();
  35167. scene.resetCachedMaterial();
  35168. // Fallbacks
  35169. var fallbacks = new BABYLON.EffectFallbacks();
  35170. if (defines.REFLECTION) {
  35171. fallbacks.addFallback(0, "REFLECTION");
  35172. }
  35173. if (defines.SPECULAR) {
  35174. fallbacks.addFallback(0, "SPECULAR");
  35175. }
  35176. if (defines.BUMP) {
  35177. fallbacks.addFallback(0, "BUMP");
  35178. }
  35179. if (defines.PARALLAX) {
  35180. fallbacks.addFallback(1, "PARALLAX");
  35181. }
  35182. if (defines.PARALLAXOCCLUSION) {
  35183. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35184. }
  35185. if (defines.SPECULAROVERALPHA) {
  35186. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35187. }
  35188. if (defines.FOG) {
  35189. fallbacks.addFallback(1, "FOG");
  35190. }
  35191. if (defines.POINTSIZE) {
  35192. fallbacks.addFallback(0, "POINTSIZE");
  35193. }
  35194. if (defines.LOGARITHMICDEPTH) {
  35195. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35196. }
  35197. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35198. if (defines.SPECULARTERM) {
  35199. fallbacks.addFallback(0, "SPECULARTERM");
  35200. }
  35201. if (defines.DIFFUSEFRESNEL) {
  35202. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35203. }
  35204. if (defines.OPACITYFRESNEL) {
  35205. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35206. }
  35207. if (defines.REFLECTIONFRESNEL) {
  35208. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35209. }
  35210. if (defines.EMISSIVEFRESNEL) {
  35211. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35212. }
  35213. if (defines.FRESNEL) {
  35214. fallbacks.addFallback(4, "FRESNEL");
  35215. }
  35216. //Attributes
  35217. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35218. if (defines.NORMAL) {
  35219. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35220. }
  35221. if (defines.UV1) {
  35222. attribs.push(BABYLON.VertexBuffer.UVKind);
  35223. }
  35224. if (defines.UV2) {
  35225. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35226. }
  35227. if (defines.VERTEXCOLOR) {
  35228. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35229. }
  35230. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35231. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35232. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35233. var shaderName = "default";
  35234. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35235. "vFogInfos", "vFogColor", "pointSize",
  35236. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35237. "mBones",
  35238. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35239. "depthValues",
  35240. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35241. "logarithmicDepthConstant"
  35242. ];
  35243. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35244. var uniformBuffers = ["Material", "Scene"];
  35245. if (defines.CAMERACOLORCURVES) {
  35246. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35247. }
  35248. if (defines.CAMERACOLORGRADING) {
  35249. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  35250. }
  35251. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35252. uniformsNames: uniforms,
  35253. uniformBuffersNames: uniformBuffers,
  35254. samplers: samplers,
  35255. defines: defines,
  35256. maxSimultaneousLights: this._maxSimultaneousLights
  35257. });
  35258. if (this.customShaderNameResolve) {
  35259. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35260. }
  35261. var join = defines.toString();
  35262. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35263. attributes: attribs,
  35264. uniformsNames: uniforms,
  35265. uniformBuffersNames: uniformBuffers,
  35266. samplers: samplers,
  35267. defines: join,
  35268. fallbacks: fallbacks,
  35269. onCompiled: this.onCompiled,
  35270. onError: this.onError,
  35271. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35272. }, engine), defines);
  35273. this.buildUniformLayout();
  35274. }
  35275. if (!subMesh.effect.isReady()) {
  35276. return false;
  35277. }
  35278. defines._renderId = scene.getRenderId();
  35279. this._wasPreviouslyReady = true;
  35280. return true;
  35281. };
  35282. StandardMaterial.prototype.buildUniformLayout = function () {
  35283. // Order is important !
  35284. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35285. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35286. this._uniformBuffer.addUniform("opacityParts", 4);
  35287. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35288. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35289. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35290. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35291. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35292. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35293. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35294. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35295. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35296. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35297. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35298. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35299. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35300. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35301. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35302. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35303. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35304. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35305. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35306. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35307. this._uniformBuffer.addUniform("specularMatrix", 16);
  35308. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35309. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35310. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35311. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35312. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35313. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35314. this._uniformBuffer.addUniform("pointSize", 1);
  35315. this._uniformBuffer.create();
  35316. };
  35317. StandardMaterial.prototype.unbind = function () {
  35318. if (this._activeEffect) {
  35319. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35320. this._activeEffect.setTexture("reflection2DSampler", null);
  35321. }
  35322. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35323. this._activeEffect.setTexture("refraction2DSampler", null);
  35324. }
  35325. }
  35326. _super.prototype.unbind.call(this);
  35327. };
  35328. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35329. var scene = this.getScene();
  35330. var defines = subMesh._materialDefines;
  35331. if (!defines) {
  35332. return;
  35333. }
  35334. var effect = subMesh.effect;
  35335. this._activeEffect = effect;
  35336. // Matrices
  35337. this.bindOnlyWorldMatrix(world);
  35338. // Bones
  35339. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35340. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35341. this._uniformBuffer.bindToEffect(effect, "Material");
  35342. this.bindViewProjection(effect);
  35343. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35344. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35345. // Fresnel
  35346. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35347. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35348. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35349. }
  35350. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35351. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35352. }
  35353. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35354. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35355. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35356. }
  35357. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35358. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35359. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35360. }
  35361. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35362. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35363. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35364. }
  35365. }
  35366. // Textures
  35367. if (scene.texturesEnabled) {
  35368. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35369. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35370. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  35371. }
  35372. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35373. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35374. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35375. }
  35376. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35377. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35378. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35379. }
  35380. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35381. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35382. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35383. }
  35384. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35385. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35386. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35387. }
  35388. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35389. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35390. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35391. }
  35392. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35393. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35394. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  35395. }
  35396. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35397. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35398. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35399. }
  35400. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35401. var depth = 1.0;
  35402. if (!this._refractionTexture.isCube) {
  35403. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35404. if (this._refractionTexture.depth) {
  35405. depth = this._refractionTexture.depth;
  35406. }
  35407. }
  35408. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35409. }
  35410. }
  35411. // Point size
  35412. if (this.pointsCloud) {
  35413. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35414. }
  35415. if (defines.SPECULARTERM) {
  35416. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35417. }
  35418. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35419. // Diffuse
  35420. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35421. }
  35422. // Textures
  35423. if (scene.texturesEnabled) {
  35424. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35425. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35426. }
  35427. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35428. effect.setTexture("ambientSampler", this._ambientTexture);
  35429. }
  35430. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35431. effect.setTexture("opacitySampler", this._opacityTexture);
  35432. }
  35433. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35434. if (this._reflectionTexture.isCube) {
  35435. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35436. }
  35437. else {
  35438. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35439. }
  35440. }
  35441. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35442. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35443. }
  35444. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35445. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35446. }
  35447. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35448. effect.setTexture("specularSampler", this._specularTexture);
  35449. }
  35450. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35451. effect.setTexture("bumpSampler", this._bumpTexture);
  35452. }
  35453. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35454. var depth = 1.0;
  35455. if (this._refractionTexture.isCube) {
  35456. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35457. }
  35458. else {
  35459. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35460. }
  35461. }
  35462. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  35463. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  35464. }
  35465. }
  35466. // Clip plane
  35467. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35468. // Colors
  35469. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35470. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35471. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35472. }
  35473. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35474. // Lights
  35475. if (scene.lightsEnabled && !this._disableLighting) {
  35476. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35477. }
  35478. // View
  35479. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35480. this.bindView(effect);
  35481. }
  35482. // Fog
  35483. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35484. // Morph targets
  35485. if (defines.NUM_MORPH_INFLUENCERS) {
  35486. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35487. }
  35488. // Log. depth
  35489. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35490. // Color Curves
  35491. if (this._cameraColorCurves) {
  35492. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  35493. }
  35494. }
  35495. this._uniformBuffer.update();
  35496. this._afterBind(mesh, this._activeEffect);
  35497. };
  35498. StandardMaterial.prototype.getAnimatables = function () {
  35499. var results = [];
  35500. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35501. results.push(this._diffuseTexture);
  35502. }
  35503. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35504. results.push(this._ambientTexture);
  35505. }
  35506. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35507. results.push(this._opacityTexture);
  35508. }
  35509. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35510. results.push(this._reflectionTexture);
  35511. }
  35512. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35513. results.push(this._emissiveTexture);
  35514. }
  35515. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35516. results.push(this._specularTexture);
  35517. }
  35518. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35519. results.push(this._bumpTexture);
  35520. }
  35521. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35522. results.push(this._lightmapTexture);
  35523. }
  35524. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35525. results.push(this._refractionTexture);
  35526. }
  35527. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  35528. results.push(this._cameraColorGradingTexture);
  35529. }
  35530. return results;
  35531. };
  35532. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35533. if (forceDisposeTextures) {
  35534. if (this._diffuseTexture) {
  35535. this._diffuseTexture.dispose();
  35536. }
  35537. if (this._ambientTexture) {
  35538. this._ambientTexture.dispose();
  35539. }
  35540. if (this._opacityTexture) {
  35541. this._opacityTexture.dispose();
  35542. }
  35543. if (this._reflectionTexture) {
  35544. this._reflectionTexture.dispose();
  35545. }
  35546. if (this._emissiveTexture) {
  35547. this._emissiveTexture.dispose();
  35548. }
  35549. if (this._specularTexture) {
  35550. this._specularTexture.dispose();
  35551. }
  35552. if (this._bumpTexture) {
  35553. this._bumpTexture.dispose();
  35554. }
  35555. if (this._lightmapTexture) {
  35556. this._lightmapTexture.dispose();
  35557. }
  35558. if (this._refractionTexture) {
  35559. this._refractionTexture.dispose();
  35560. }
  35561. if (this._cameraColorGradingTexture) {
  35562. this._cameraColorGradingTexture.dispose();
  35563. }
  35564. }
  35565. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35566. };
  35567. StandardMaterial.prototype.clone = function (name) {
  35568. var _this = this;
  35569. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35570. result.name = name;
  35571. result.id = name;
  35572. return result;
  35573. };
  35574. StandardMaterial.prototype.serialize = function () {
  35575. return BABYLON.SerializationHelper.Serialize(this);
  35576. };
  35577. // Statics
  35578. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35579. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35580. };
  35581. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35582. get: function () {
  35583. return StandardMaterial._DiffuseTextureEnabled;
  35584. },
  35585. set: function (value) {
  35586. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35587. return;
  35588. }
  35589. StandardMaterial._DiffuseTextureEnabled = value;
  35590. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35591. },
  35592. enumerable: true,
  35593. configurable: true
  35594. });
  35595. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35596. get: function () {
  35597. return StandardMaterial._AmbientTextureEnabled;
  35598. },
  35599. set: function (value) {
  35600. if (StandardMaterial._AmbientTextureEnabled === value) {
  35601. return;
  35602. }
  35603. StandardMaterial._AmbientTextureEnabled = value;
  35604. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35605. },
  35606. enumerable: true,
  35607. configurable: true
  35608. });
  35609. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35610. get: function () {
  35611. return StandardMaterial._OpacityTextureEnabled;
  35612. },
  35613. set: function (value) {
  35614. if (StandardMaterial._OpacityTextureEnabled === value) {
  35615. return;
  35616. }
  35617. StandardMaterial._OpacityTextureEnabled = value;
  35618. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35619. },
  35620. enumerable: true,
  35621. configurable: true
  35622. });
  35623. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35624. get: function () {
  35625. return StandardMaterial._ReflectionTextureEnabled;
  35626. },
  35627. set: function (value) {
  35628. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35629. return;
  35630. }
  35631. StandardMaterial._ReflectionTextureEnabled = value;
  35632. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35633. },
  35634. enumerable: true,
  35635. configurable: true
  35636. });
  35637. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35638. get: function () {
  35639. return StandardMaterial._EmissiveTextureEnabled;
  35640. },
  35641. set: function (value) {
  35642. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35643. return;
  35644. }
  35645. StandardMaterial._EmissiveTextureEnabled = value;
  35646. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35647. },
  35648. enumerable: true,
  35649. configurable: true
  35650. });
  35651. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35652. get: function () {
  35653. return StandardMaterial._SpecularTextureEnabled;
  35654. },
  35655. set: function (value) {
  35656. if (StandardMaterial._SpecularTextureEnabled === value) {
  35657. return;
  35658. }
  35659. StandardMaterial._SpecularTextureEnabled = value;
  35660. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35661. },
  35662. enumerable: true,
  35663. configurable: true
  35664. });
  35665. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35666. get: function () {
  35667. return StandardMaterial._BumpTextureEnabled;
  35668. },
  35669. set: function (value) {
  35670. if (StandardMaterial._BumpTextureEnabled === value) {
  35671. return;
  35672. }
  35673. StandardMaterial._BumpTextureEnabled = value;
  35674. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35675. },
  35676. enumerable: true,
  35677. configurable: true
  35678. });
  35679. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35680. get: function () {
  35681. return StandardMaterial._LightmapTextureEnabled;
  35682. },
  35683. set: function (value) {
  35684. if (StandardMaterial._LightmapTextureEnabled === value) {
  35685. return;
  35686. }
  35687. StandardMaterial._LightmapTextureEnabled = value;
  35688. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35689. },
  35690. enumerable: true,
  35691. configurable: true
  35692. });
  35693. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35694. get: function () {
  35695. return StandardMaterial._RefractionTextureEnabled;
  35696. },
  35697. set: function (value) {
  35698. if (StandardMaterial._RefractionTextureEnabled === value) {
  35699. return;
  35700. }
  35701. StandardMaterial._RefractionTextureEnabled = value;
  35702. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35703. },
  35704. enumerable: true,
  35705. configurable: true
  35706. });
  35707. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35708. get: function () {
  35709. return StandardMaterial._ColorGradingTextureEnabled;
  35710. },
  35711. set: function (value) {
  35712. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35713. return;
  35714. }
  35715. StandardMaterial._ColorGradingTextureEnabled = value;
  35716. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35717. },
  35718. enumerable: true,
  35719. configurable: true
  35720. });
  35721. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35722. get: function () {
  35723. return StandardMaterial._FresnelEnabled;
  35724. },
  35725. set: function (value) {
  35726. if (StandardMaterial._FresnelEnabled === value) {
  35727. return;
  35728. }
  35729. StandardMaterial._FresnelEnabled = value;
  35730. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35731. },
  35732. enumerable: true,
  35733. configurable: true
  35734. });
  35735. return StandardMaterial;
  35736. }(BABYLON.PushMaterial));
  35737. // Flags used to enable or disable a type of texture for all Standard Materials
  35738. StandardMaterial._DiffuseTextureEnabled = true;
  35739. StandardMaterial._AmbientTextureEnabled = true;
  35740. StandardMaterial._OpacityTextureEnabled = true;
  35741. StandardMaterial._ReflectionTextureEnabled = true;
  35742. StandardMaterial._EmissiveTextureEnabled = true;
  35743. StandardMaterial._SpecularTextureEnabled = true;
  35744. StandardMaterial._BumpTextureEnabled = true;
  35745. StandardMaterial._LightmapTextureEnabled = true;
  35746. StandardMaterial._RefractionTextureEnabled = true;
  35747. StandardMaterial._ColorGradingTextureEnabled = true;
  35748. StandardMaterial._FresnelEnabled = true;
  35749. __decorate([
  35750. BABYLON.serializeAsTexture("diffuseTexture")
  35751. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35752. __decorate([
  35753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35754. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35755. __decorate([
  35756. BABYLON.serializeAsTexture("ambientTexture")
  35757. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35758. __decorate([
  35759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35760. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35761. __decorate([
  35762. BABYLON.serializeAsTexture("opacityTexture")
  35763. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35764. __decorate([
  35765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35766. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35767. __decorate([
  35768. BABYLON.serializeAsTexture("reflectionTexture")
  35769. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35770. __decorate([
  35771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35772. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35773. __decorate([
  35774. BABYLON.serializeAsTexture("emissiveTexture")
  35775. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35776. __decorate([
  35777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35778. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35779. __decorate([
  35780. BABYLON.serializeAsTexture("specularTexture")
  35781. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35782. __decorate([
  35783. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35784. ], StandardMaterial.prototype, "specularTexture", void 0);
  35785. __decorate([
  35786. BABYLON.serializeAsTexture("bumpTexture")
  35787. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35788. __decorate([
  35789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35790. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35791. __decorate([
  35792. BABYLON.serializeAsTexture("lightmapTexture")
  35793. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35794. __decorate([
  35795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35796. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35797. __decorate([
  35798. BABYLON.serializeAsTexture("refractionTexture")
  35799. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35800. __decorate([
  35801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35802. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35803. __decorate([
  35804. BABYLON.serializeAsColor3("ambient")
  35805. ], StandardMaterial.prototype, "ambientColor", void 0);
  35806. __decorate([
  35807. BABYLON.serializeAsColor3("diffuse")
  35808. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35809. __decorate([
  35810. BABYLON.serializeAsColor3("specular")
  35811. ], StandardMaterial.prototype, "specularColor", void 0);
  35812. __decorate([
  35813. BABYLON.serializeAsColor3("emissive")
  35814. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35815. __decorate([
  35816. BABYLON.serialize()
  35817. ], StandardMaterial.prototype, "specularPower", void 0);
  35818. __decorate([
  35819. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35820. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35821. __decorate([
  35822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35823. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35824. __decorate([
  35825. BABYLON.serialize("useEmissiveAsIllumination")
  35826. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35827. __decorate([
  35828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35829. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35830. __decorate([
  35831. BABYLON.serialize("linkEmissiveWithDiffuse")
  35832. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35833. __decorate([
  35834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35835. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35836. __decorate([
  35837. BABYLON.serialize("useSpecularOverAlpha")
  35838. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35839. __decorate([
  35840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35841. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35842. __decorate([
  35843. BABYLON.serialize("useReflectionOverAlpha")
  35844. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35845. __decorate([
  35846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35847. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35848. __decorate([
  35849. BABYLON.serialize("disableLighting")
  35850. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35851. __decorate([
  35852. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35853. ], StandardMaterial.prototype, "disableLighting", void 0);
  35854. __decorate([
  35855. BABYLON.serialize("useParallax")
  35856. ], StandardMaterial.prototype, "_useParallax", void 0);
  35857. __decorate([
  35858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35859. ], StandardMaterial.prototype, "useParallax", void 0);
  35860. __decorate([
  35861. BABYLON.serialize("useParallaxOcclusion")
  35862. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35863. __decorate([
  35864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35865. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35866. __decorate([
  35867. BABYLON.serialize()
  35868. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35869. __decorate([
  35870. BABYLON.serialize("roughness")
  35871. ], StandardMaterial.prototype, "_roughness", void 0);
  35872. __decorate([
  35873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35874. ], StandardMaterial.prototype, "roughness", void 0);
  35875. __decorate([
  35876. BABYLON.serialize()
  35877. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35878. __decorate([
  35879. BABYLON.serialize()
  35880. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35881. __decorate([
  35882. BABYLON.serialize("useLightmapAsShadowmap")
  35883. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35884. __decorate([
  35885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35886. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35887. __decorate([
  35888. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35889. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35890. __decorate([
  35891. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35892. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35893. __decorate([
  35894. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35895. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35896. __decorate([
  35897. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35898. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35899. __decorate([
  35900. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35901. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35902. __decorate([
  35903. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35904. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35905. __decorate([
  35906. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35907. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35908. __decorate([
  35909. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35910. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35911. __decorate([
  35912. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35913. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35914. __decorate([
  35915. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35916. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35917. __decorate([
  35918. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35919. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35920. __decorate([
  35921. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35922. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35923. __decorate([
  35924. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35925. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35926. __decorate([
  35927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35928. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35929. __decorate([
  35930. BABYLON.serialize("maxSimultaneousLights")
  35931. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35932. __decorate([
  35933. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35934. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35935. __decorate([
  35936. BABYLON.serialize("invertNormalMapX")
  35937. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35938. __decorate([
  35939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35940. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35941. __decorate([
  35942. BABYLON.serialize("invertNormalMapY")
  35943. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35944. __decorate([
  35945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35946. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35947. __decorate([
  35948. BABYLON.serialize("twoSidedLighting")
  35949. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35950. __decorate([
  35951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35952. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35953. __decorate([
  35954. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  35955. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  35956. __decorate([
  35957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35958. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  35959. __decorate([
  35960. BABYLON.serializeAsColorCurves("cameraColorCurves")
  35961. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  35962. __decorate([
  35963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35964. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  35965. __decorate([
  35966. BABYLON.serialize()
  35967. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35968. BABYLON.StandardMaterial = StandardMaterial;
  35969. })(BABYLON || (BABYLON = {}));
  35970. //# sourceMappingURL=babylon.standardMaterial.js.map
  35971. var BABYLON;
  35972. (function (BABYLON) {
  35973. /**
  35974. * This class implement a typical dictionary using a string as key and the generic type T as value.
  35975. * The underlying implementation relies on an associative array to ensure the best performances.
  35976. * The value can be anything including 'null' but except 'undefined'
  35977. */
  35978. var StringDictionary = (function () {
  35979. function StringDictionary() {
  35980. this._count = 0;
  35981. this._data = {};
  35982. }
  35983. /**
  35984. * This will clear this dictionary and copy the content from the 'source' one.
  35985. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  35986. * @param source the dictionary to take the content from and copy to this dictionary
  35987. */
  35988. StringDictionary.prototype.copyFrom = function (source) {
  35989. var _this = this;
  35990. this.clear();
  35991. source.forEach(function (t, v) { return _this.add(t, v); });
  35992. };
  35993. /**
  35994. * Get a value based from its key
  35995. * @param key the given key to get the matching value from
  35996. * @return the value if found, otherwise undefined is returned
  35997. */
  35998. StringDictionary.prototype.get = function (key) {
  35999. var val = this._data[key];
  36000. if (val !== undefined) {
  36001. return val;
  36002. }
  36003. return undefined;
  36004. };
  36005. /**
  36006. * Get a value from its key or add it if it doesn't exist.
  36007. * This method will ensure you that a given key/data will be present in the dictionary.
  36008. * @param key the given key to get the matching value from
  36009. * @param factory the factory that will create the value if the key is not present in the dictionary.
  36010. * The factory will only be invoked if there's no data for the given key.
  36011. * @return the value corresponding to the key.
  36012. */
  36013. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  36014. var val = this.get(key);
  36015. if (val !== undefined) {
  36016. return val;
  36017. }
  36018. val = factory(key);
  36019. if (val) {
  36020. this.add(key, val);
  36021. }
  36022. return val;
  36023. };
  36024. /**
  36025. * Get a value from its key if present in the dictionary otherwise add it
  36026. * @param key the key to get the value from
  36027. * @param val if there's no such key/value pair in the dictionary add it with this value
  36028. * @return the value corresponding to the key
  36029. */
  36030. StringDictionary.prototype.getOrAdd = function (key, val) {
  36031. var curVal = this.get(key);
  36032. if (curVal !== undefined) {
  36033. return curVal;
  36034. }
  36035. this.add(key, val);
  36036. return val;
  36037. };
  36038. /**
  36039. * Check if there's a given key in the dictionary
  36040. * @param key the key to check for
  36041. * @return true if the key is present, false otherwise
  36042. */
  36043. StringDictionary.prototype.contains = function (key) {
  36044. return this._data[key] !== undefined;
  36045. };
  36046. /**
  36047. * Add a new key and its corresponding value
  36048. * @param key the key to add
  36049. * @param value the value corresponding to the key
  36050. * @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
  36051. */
  36052. StringDictionary.prototype.add = function (key, value) {
  36053. if (this._data[key] !== undefined) {
  36054. return false;
  36055. }
  36056. this._data[key] = value;
  36057. ++this._count;
  36058. return true;
  36059. };
  36060. StringDictionary.prototype.set = function (key, value) {
  36061. if (this._data[key] === undefined) {
  36062. return false;
  36063. }
  36064. this._data[key] = value;
  36065. return true;
  36066. };
  36067. /**
  36068. * Get the element of the given key and remove it from the dictionary
  36069. * @param key
  36070. */
  36071. StringDictionary.prototype.getAndRemove = function (key) {
  36072. var val = this.get(key);
  36073. if (val !== undefined) {
  36074. delete this._data[key];
  36075. --this._count;
  36076. return val;
  36077. }
  36078. return null;
  36079. };
  36080. /**
  36081. * Remove a key/value from the dictionary.
  36082. * @param key the key to remove
  36083. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  36084. */
  36085. StringDictionary.prototype.remove = function (key) {
  36086. if (this.contains(key)) {
  36087. delete this._data[key];
  36088. --this._count;
  36089. return true;
  36090. }
  36091. return false;
  36092. };
  36093. /**
  36094. * Clear the whole content of the dictionary
  36095. */
  36096. StringDictionary.prototype.clear = function () {
  36097. this._data = {};
  36098. this._count = 0;
  36099. };
  36100. Object.defineProperty(StringDictionary.prototype, "count", {
  36101. get: function () {
  36102. return this._count;
  36103. },
  36104. enumerable: true,
  36105. configurable: true
  36106. });
  36107. /**
  36108. * Execute a callback on each key/val of the dictionary.
  36109. * Note that you can remove any element in this dictionary in the callback implementation
  36110. * @param callback the callback to execute on a given key/value pair
  36111. */
  36112. StringDictionary.prototype.forEach = function (callback) {
  36113. for (var cur in this._data) {
  36114. var val = this._data[cur];
  36115. callback(cur, val);
  36116. }
  36117. };
  36118. /**
  36119. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  36120. * If the callback returns null or undefined the method will iterate to the next key/value pair
  36121. * Note that you can remove any element in this dictionary in the callback implementation
  36122. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  36123. */
  36124. StringDictionary.prototype.first = function (callback) {
  36125. for (var cur in this._data) {
  36126. var val = this._data[cur];
  36127. var res = callback(cur, val);
  36128. if (res) {
  36129. return res;
  36130. }
  36131. }
  36132. return null;
  36133. };
  36134. return StringDictionary;
  36135. }());
  36136. BABYLON.StringDictionary = StringDictionary;
  36137. })(BABYLON || (BABYLON = {}));
  36138. //# sourceMappingURL=babylon.stringDictionary.js.map
  36139. var BABYLON;
  36140. (function (BABYLON) {
  36141. var DynamicFloatArrayElementInfo = (function () {
  36142. function DynamicFloatArrayElementInfo() {
  36143. }
  36144. return DynamicFloatArrayElementInfo;
  36145. }());
  36146. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  36147. /**
  36148. * 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.
  36149. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  36150. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  36151. * 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.
  36152. * 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.
  36153. * 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".
  36154. */
  36155. var DynamicFloatArray = (function () {
  36156. /**
  36157. * Construct an instance of the dynamic float array
  36158. * @param stride size of one element in float (i.e. not bytes!)
  36159. * @param initialElementCount the number of available entries at construction
  36160. */
  36161. function DynamicFloatArray(stride, initialElementCount) {
  36162. this.compareValueOffset = null;
  36163. this.sortingAscending = true;
  36164. this._stride = stride;
  36165. this.buffer = new Float32Array(stride * initialElementCount);
  36166. this._lastUsed = 0;
  36167. this._firstFree = 0;
  36168. this._allEntries = new Array(initialElementCount);
  36169. this._freeEntries = new Array(initialElementCount);
  36170. for (var i = 0; i < initialElementCount; i++) {
  36171. var element = new DynamicFloatArrayElementInfo();
  36172. element.offset = i * stride;
  36173. this._allEntries[i] = element;
  36174. this._freeEntries[initialElementCount - i - 1] = element;
  36175. }
  36176. }
  36177. /**
  36178. * Allocate an element in the array.
  36179. * @return the element info instance that contains the offset into the main buffer of the element's location.
  36180. * Beware, this offset may change when you call pack()
  36181. */
  36182. DynamicFloatArray.prototype.allocElement = function () {
  36183. if (this._freeEntries.length === 0) {
  36184. this._growBuffer();
  36185. }
  36186. var el = this._freeEntries.pop();
  36187. this._lastUsed = Math.max(el.offset, this._lastUsed);
  36188. if (el.offset === this._firstFree) {
  36189. if (this._freeEntries.length > 0) {
  36190. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  36191. }
  36192. else {
  36193. this._firstFree += this._stride;
  36194. }
  36195. }
  36196. return el;
  36197. };
  36198. /**
  36199. * Free the element corresponding to the given element info
  36200. * @param elInfo the element that describe the allocated element
  36201. */
  36202. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  36203. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  36204. this._freeEntries.push(elInfo);
  36205. };
  36206. /**
  36207. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  36208. * 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().
  36209. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  36210. */
  36211. DynamicFloatArray.prototype.pack = function () {
  36212. // no free slot? no need to pack
  36213. if (this._freeEntries.length === 0) {
  36214. return this.buffer;
  36215. }
  36216. // If the buffer is already packed the last used will always be lower than the first free
  36217. // 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.
  36218. if (this._lastUsed < this._firstFree) {
  36219. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  36220. return elementsBuffer_1;
  36221. }
  36222. var s = this._stride;
  36223. // 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
  36224. var lastFree = new DynamicFloatArrayElementInfo();
  36225. lastFree.offset = this.totalElementCount * s;
  36226. this._freeEntries.push(lastFree);
  36227. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  36228. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36229. var firstFreeSlotOffset = sortedFree[0].offset;
  36230. var freeZoneSize = 1;
  36231. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  36232. var prevOffset = sortedFree[0].offset;
  36233. for (var i = 1; i < sortedFree.length; i++) {
  36234. // 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
  36235. if (firstFreeSlotOffset >= occupiedZoneSize) {
  36236. break;
  36237. }
  36238. var curFree = sortedFree[i];
  36239. var curOffset = curFree.offset;
  36240. // Compute the distance between this offset and the previous
  36241. var distance = curOffset - prevOffset;
  36242. // If the distance is the stride size, they are adjacent, it good, move to the next
  36243. if (distance === s) {
  36244. // Free zone is one element bigger
  36245. ++freeZoneSize;
  36246. // as we're about to iterate to the next, the cur becomes the previous...
  36247. prevOffset = curOffset;
  36248. continue;
  36249. }
  36250. // Distance is bigger, which means there's x element between the previous free and this one
  36251. var usedRange = (distance / s) - 1;
  36252. // Two cases the free zone is smaller than the data to move or bigger
  36253. // Copy what can fit in the free zone
  36254. var curMoveOffset = curOffset - s;
  36255. var copyCount = Math.min(freeZoneSize, usedRange);
  36256. for (var j = 0; j < copyCount; j++) {
  36257. var freeI = firstFreeSlotOffset / s;
  36258. var curI = curMoveOffset / s;
  36259. var moveEl = sortedAll[curI];
  36260. this._moveElement(moveEl, firstFreeSlotOffset);
  36261. var replacedEl = sortedAll[freeI];
  36262. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  36263. replacedEl.offset = curMoveOffset;
  36264. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  36265. sortedAll[freeI] = moveEl;
  36266. sortedAll[curI] = replacedEl;
  36267. curMoveOffset -= s;
  36268. firstFreeSlotOffset += s;
  36269. }
  36270. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  36271. if (freeZoneSize <= usedRange) {
  36272. firstFreeSlotOffset = curMoveOffset + s;
  36273. freeZoneSize = 1 + copyCount;
  36274. }
  36275. else {
  36276. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  36277. }
  36278. // as we're about to iterate to the next, the cur becomes the previous...
  36279. prevOffset = curOffset;
  36280. }
  36281. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  36282. this._lastUsed = firstFreeSlotOffset - s;
  36283. this._firstFree = firstFreeSlotOffset;
  36284. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  36285. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  36286. this._allEntries = sortedAll;
  36287. return elementsBuffer;
  36288. };
  36289. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  36290. for (var i = 0; i < this._stride; i++) {
  36291. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  36292. }
  36293. element.offset = destOffset;
  36294. };
  36295. DynamicFloatArray.prototype._growBuffer = function () {
  36296. // Allocate the new buffer with 50% more entries, copy the content of the current one
  36297. var newElCount = Math.floor(this.totalElementCount * 1.5);
  36298. var newBuffer = new Float32Array(newElCount * this._stride);
  36299. newBuffer.set(this.buffer);
  36300. var curCount = this.totalElementCount;
  36301. var addedCount = newElCount - this.totalElementCount;
  36302. for (var i = 0; i < addedCount; i++) {
  36303. var element = new DynamicFloatArrayElementInfo();
  36304. element.offset = (curCount + i) * this.stride;
  36305. this._allEntries.push(element);
  36306. this._freeEntries[addedCount - i - 1] = element;
  36307. }
  36308. this._firstFree = curCount * this.stride;
  36309. this.buffer = newBuffer;
  36310. };
  36311. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  36312. /**
  36313. * Get the total count of entries that can fit in the current buffer
  36314. * @returns the elements count
  36315. */
  36316. get: function () {
  36317. return this._allEntries.length;
  36318. },
  36319. enumerable: true,
  36320. configurable: true
  36321. });
  36322. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  36323. /**
  36324. * Get the count of free entries that can still be allocated without resizing the buffer
  36325. * @returns the free elements count
  36326. */
  36327. get: function () {
  36328. return this._freeEntries.length;
  36329. },
  36330. enumerable: true,
  36331. configurable: true
  36332. });
  36333. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36334. /**
  36335. * Get the count of allocated elements
  36336. * @returns the allocated elements count
  36337. */
  36338. get: function () {
  36339. return this._allEntries.length - this._freeEntries.length;
  36340. },
  36341. enumerable: true,
  36342. configurable: true
  36343. });
  36344. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36345. /**
  36346. * Return the size of one element in float
  36347. * @returns the size in float
  36348. */
  36349. get: function () {
  36350. return this._stride;
  36351. },
  36352. enumerable: true,
  36353. configurable: true
  36354. });
  36355. DynamicFloatArray.prototype.sort = function () {
  36356. var _this = this;
  36357. if (!this.compareValueOffset) {
  36358. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36359. }
  36360. var count = this.usedElementCount;
  36361. // Do we have to (re)create the sort table?
  36362. if (!this._sortTable || this._sortTable.length < count) {
  36363. // 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...
  36364. var newCount = Math.min(this.totalElementCount, count * 2);
  36365. this._sortTable = new Array(newCount);
  36366. }
  36367. if (!this._sortedTable || this._sortedTable.length !== count) {
  36368. this._sortedTable = new Array(count);
  36369. }
  36370. // Because, you know...
  36371. this.pack();
  36372. //let stride = this.stride;
  36373. //for (let i = 0; i < count; i++) {
  36374. // let si = this._sortTable[i];
  36375. // if (!si) {
  36376. // si = new SortInfo();
  36377. // this._sortTable[i] = si;
  36378. // }
  36379. // si.entry = this._allEntries[i];
  36380. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36381. // si.swapedOffset = null;
  36382. // this._sortedTable[i] = si;
  36383. //}
  36384. var curOffset = 0;
  36385. var stride = this.stride;
  36386. for (var i = 0; i < count; i++, curOffset += stride) {
  36387. var si = this._sortTable[i];
  36388. if (!si) {
  36389. si = new SortInfo();
  36390. this._sortTable[i] = si;
  36391. }
  36392. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36393. si.offset = curOffset;
  36394. si.swapedOffset = null;
  36395. this._sortedTable[i] = si;
  36396. }
  36397. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36398. if (this.sortingAscending) {
  36399. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36400. }
  36401. else {
  36402. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36403. }
  36404. var swapElements = function (src, dst) {
  36405. for (var i = 0; i < stride; i++) {
  36406. var tps = _this.buffer[dst + i];
  36407. _this.buffer[dst + i] = _this.buffer[src + i];
  36408. _this.buffer[src + i] = tps;
  36409. }
  36410. };
  36411. // 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:
  36412. // 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),
  36413. // and I still want something with a good algorithm complexity.
  36414. // 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,
  36415. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36416. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36417. // 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
  36418. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36419. // 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
  36420. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36421. for (var i = 0; i < count; i++) {
  36422. // Get the element to move
  36423. var sourceSI = this._sortedTable[i];
  36424. var destSI = this._sortTable[i];
  36425. var sourceOff = sourceSI.offset;
  36426. // If the source changed location, find the new one
  36427. if (sourceSI.swapedOffset) {
  36428. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36429. var curSI = sourceSI;
  36430. while (curSI.swapedOffset) {
  36431. curSI = this._sortTable[curSI.swapedOffset / stride];
  36432. }
  36433. // Finally get the right location
  36434. sourceOff = curSI.offset;
  36435. }
  36436. // Tag the element being replaced with its new location
  36437. destSI.swapedOffset = sourceOff;
  36438. // Swap elements (only if needed)
  36439. if (sourceOff !== destSI.offset) {
  36440. swapElements(sourceOff, destSI.offset);
  36441. }
  36442. // Update the offset in the corresponding DFAE
  36443. //sourceSI.entry.offset = destSI.entry.offset;
  36444. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36445. }
  36446. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36447. return true;
  36448. };
  36449. return DynamicFloatArray;
  36450. }());
  36451. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36452. var SortInfo = (function () {
  36453. function SortInfo() {
  36454. this.compareData = this.offset = this.swapedOffset = null;
  36455. }
  36456. return SortInfo;
  36457. }());
  36458. })(BABYLON || (BABYLON = {}));
  36459. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  36460. var BABYLON;
  36461. (function (BABYLON) {
  36462. var Condition = (function () {
  36463. function Condition(actionManager) {
  36464. this._actionManager = actionManager;
  36465. }
  36466. Condition.prototype.isValid = function () {
  36467. return true;
  36468. };
  36469. Condition.prototype._getProperty = function (propertyPath) {
  36470. return this._actionManager._getProperty(propertyPath);
  36471. };
  36472. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36473. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36474. };
  36475. Condition.prototype.serialize = function () {
  36476. };
  36477. Condition.prototype._serialize = function (serializedCondition) {
  36478. return {
  36479. type: 2,
  36480. children: [],
  36481. name: serializedCondition.name,
  36482. properties: serializedCondition.properties
  36483. };
  36484. };
  36485. return Condition;
  36486. }());
  36487. BABYLON.Condition = Condition;
  36488. var ValueCondition = (function (_super) {
  36489. __extends(ValueCondition, _super);
  36490. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36491. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36492. var _this = _super.call(this, actionManager) || this;
  36493. _this.propertyPath = propertyPath;
  36494. _this.value = value;
  36495. _this.operator = operator;
  36496. _this._target = target;
  36497. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36498. _this._property = _this._getProperty(_this.propertyPath);
  36499. return _this;
  36500. }
  36501. Object.defineProperty(ValueCondition, "IsEqual", {
  36502. get: function () {
  36503. return ValueCondition._IsEqual;
  36504. },
  36505. enumerable: true,
  36506. configurable: true
  36507. });
  36508. Object.defineProperty(ValueCondition, "IsDifferent", {
  36509. get: function () {
  36510. return ValueCondition._IsDifferent;
  36511. },
  36512. enumerable: true,
  36513. configurable: true
  36514. });
  36515. Object.defineProperty(ValueCondition, "IsGreater", {
  36516. get: function () {
  36517. return ValueCondition._IsGreater;
  36518. },
  36519. enumerable: true,
  36520. configurable: true
  36521. });
  36522. Object.defineProperty(ValueCondition, "IsLesser", {
  36523. get: function () {
  36524. return ValueCondition._IsLesser;
  36525. },
  36526. enumerable: true,
  36527. configurable: true
  36528. });
  36529. // Methods
  36530. ValueCondition.prototype.isValid = function () {
  36531. switch (this.operator) {
  36532. case ValueCondition.IsGreater:
  36533. return this._effectiveTarget[this._property] > this.value;
  36534. case ValueCondition.IsLesser:
  36535. return this._effectiveTarget[this._property] < this.value;
  36536. case ValueCondition.IsEqual:
  36537. case ValueCondition.IsDifferent:
  36538. var check;
  36539. if (this.value.equals) {
  36540. check = this.value.equals(this._effectiveTarget[this._property]);
  36541. }
  36542. else {
  36543. check = this.value === this._effectiveTarget[this._property];
  36544. }
  36545. return this.operator === ValueCondition.IsEqual ? check : !check;
  36546. }
  36547. return false;
  36548. };
  36549. ValueCondition.prototype.serialize = function () {
  36550. return this._serialize({
  36551. name: "ValueCondition",
  36552. properties: [
  36553. BABYLON.Action._GetTargetProperty(this._target),
  36554. { name: "propertyPath", value: this.propertyPath },
  36555. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36556. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36557. ]
  36558. });
  36559. };
  36560. ValueCondition.GetOperatorName = function (operator) {
  36561. switch (operator) {
  36562. case ValueCondition._IsEqual: return "IsEqual";
  36563. case ValueCondition._IsDifferent: return "IsDifferent";
  36564. case ValueCondition._IsGreater: return "IsGreater";
  36565. case ValueCondition._IsLesser: return "IsLesser";
  36566. default: return "";
  36567. }
  36568. };
  36569. return ValueCondition;
  36570. }(Condition));
  36571. // Statics
  36572. ValueCondition._IsEqual = 0;
  36573. ValueCondition._IsDifferent = 1;
  36574. ValueCondition._IsGreater = 2;
  36575. ValueCondition._IsLesser = 3;
  36576. BABYLON.ValueCondition = ValueCondition;
  36577. var PredicateCondition = (function (_super) {
  36578. __extends(PredicateCondition, _super);
  36579. function PredicateCondition(actionManager, predicate) {
  36580. var _this = _super.call(this, actionManager) || this;
  36581. _this.predicate = predicate;
  36582. return _this;
  36583. }
  36584. PredicateCondition.prototype.isValid = function () {
  36585. return this.predicate();
  36586. };
  36587. return PredicateCondition;
  36588. }(Condition));
  36589. BABYLON.PredicateCondition = PredicateCondition;
  36590. var StateCondition = (function (_super) {
  36591. __extends(StateCondition, _super);
  36592. function StateCondition(actionManager, target, value) {
  36593. var _this = _super.call(this, actionManager) || this;
  36594. _this.value = value;
  36595. _this._target = target;
  36596. return _this;
  36597. }
  36598. // Methods
  36599. StateCondition.prototype.isValid = function () {
  36600. return this._target.state === this.value;
  36601. };
  36602. StateCondition.prototype.serialize = function () {
  36603. return this._serialize({
  36604. name: "StateCondition",
  36605. properties: [
  36606. BABYLON.Action._GetTargetProperty(this._target),
  36607. { name: "value", value: this.value }
  36608. ]
  36609. });
  36610. };
  36611. return StateCondition;
  36612. }(Condition));
  36613. BABYLON.StateCondition = StateCondition;
  36614. })(BABYLON || (BABYLON = {}));
  36615. //# sourceMappingURL=babylon.condition.js.map
  36616. var BABYLON;
  36617. (function (BABYLON) {
  36618. var Action = (function () {
  36619. function Action(triggerOptions, condition) {
  36620. this.triggerOptions = triggerOptions;
  36621. if (triggerOptions.parameter) {
  36622. this.trigger = triggerOptions.trigger;
  36623. this._triggerParameter = triggerOptions.parameter;
  36624. }
  36625. else {
  36626. this.trigger = triggerOptions;
  36627. }
  36628. this._nextActiveAction = this;
  36629. this._condition = condition;
  36630. }
  36631. // Methods
  36632. Action.prototype._prepare = function () {
  36633. };
  36634. Action.prototype.getTriggerParameter = function () {
  36635. return this._triggerParameter;
  36636. };
  36637. Action.prototype._executeCurrent = function (evt) {
  36638. if (this._nextActiveAction._condition) {
  36639. var condition = this._nextActiveAction._condition;
  36640. var currentRenderId = this._actionManager.getScene().getRenderId();
  36641. // We cache the current evaluation for the current frame
  36642. if (condition._evaluationId === currentRenderId) {
  36643. if (!condition._currentResult) {
  36644. return;
  36645. }
  36646. }
  36647. else {
  36648. condition._evaluationId = currentRenderId;
  36649. if (!condition.isValid()) {
  36650. condition._currentResult = false;
  36651. return;
  36652. }
  36653. condition._currentResult = true;
  36654. }
  36655. }
  36656. this._nextActiveAction.execute(evt);
  36657. this.skipToNextActiveAction();
  36658. };
  36659. Action.prototype.execute = function (evt) {
  36660. };
  36661. Action.prototype.skipToNextActiveAction = function () {
  36662. if (this._nextActiveAction._child) {
  36663. if (!this._nextActiveAction._child._actionManager) {
  36664. this._nextActiveAction._child._actionManager = this._actionManager;
  36665. }
  36666. this._nextActiveAction = this._nextActiveAction._child;
  36667. }
  36668. else {
  36669. this._nextActiveAction = this;
  36670. }
  36671. };
  36672. Action.prototype.then = function (action) {
  36673. this._child = action;
  36674. action._actionManager = this._actionManager;
  36675. action._prepare();
  36676. return action;
  36677. };
  36678. Action.prototype._getProperty = function (propertyPath) {
  36679. return this._actionManager._getProperty(propertyPath);
  36680. };
  36681. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36682. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36683. };
  36684. Action.prototype.serialize = function (parent) {
  36685. };
  36686. // Called by BABYLON.Action objects in serialize(...). Internal use
  36687. Action.prototype._serialize = function (serializedAction, parent) {
  36688. var serializationObject = {
  36689. type: 1,
  36690. children: [],
  36691. name: serializedAction.name,
  36692. properties: serializedAction.properties || []
  36693. };
  36694. // Serialize child
  36695. if (this._child) {
  36696. this._child.serialize(serializationObject);
  36697. }
  36698. // Check if "this" has a condition
  36699. if (this._condition) {
  36700. var serializedCondition = this._condition.serialize();
  36701. serializedCondition.children.push(serializationObject);
  36702. if (parent) {
  36703. parent.children.push(serializedCondition);
  36704. }
  36705. return serializedCondition;
  36706. }
  36707. if (parent) {
  36708. parent.children.push(serializationObject);
  36709. }
  36710. return serializationObject;
  36711. };
  36712. return Action;
  36713. }());
  36714. Action._SerializeValueAsString = function (value) {
  36715. if (typeof value === "number") {
  36716. return value.toString();
  36717. }
  36718. if (typeof value === "boolean") {
  36719. return value ? "true" : "false";
  36720. }
  36721. if (value instanceof BABYLON.Vector2) {
  36722. return value.x + ", " + value.y;
  36723. }
  36724. if (value instanceof BABYLON.Vector3) {
  36725. return value.x + ", " + value.y + ", " + value.z;
  36726. }
  36727. if (value instanceof BABYLON.Color3) {
  36728. return value.r + ", " + value.g + ", " + value.b;
  36729. }
  36730. if (value instanceof BABYLON.Color4) {
  36731. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36732. }
  36733. return value; // string
  36734. };
  36735. Action._GetTargetProperty = function (target) {
  36736. return {
  36737. name: "target",
  36738. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36739. : target instanceof BABYLON.Light ? "LightProperties"
  36740. : target instanceof BABYLON.Camera ? "CameraProperties"
  36741. : "SceneProperties",
  36742. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36743. };
  36744. };
  36745. BABYLON.Action = Action;
  36746. })(BABYLON || (BABYLON = {}));
  36747. //# sourceMappingURL=babylon.action.js.map
  36748. var BABYLON;
  36749. (function (BABYLON) {
  36750. /**
  36751. * ActionEvent is the event beint sent when an action is triggered.
  36752. */
  36753. var ActionEvent = (function () {
  36754. /**
  36755. * @constructor
  36756. * @param source The mesh or sprite that triggered the action.
  36757. * @param pointerX The X mouse cursor position at the time of the event
  36758. * @param pointerY The Y mouse cursor position at the time of the event
  36759. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36760. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36761. */
  36762. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36763. this.source = source;
  36764. this.pointerX = pointerX;
  36765. this.pointerY = pointerY;
  36766. this.meshUnderPointer = meshUnderPointer;
  36767. this.sourceEvent = sourceEvent;
  36768. this.additionalData = additionalData;
  36769. }
  36770. /**
  36771. * Helper function to auto-create an ActionEvent from a source mesh.
  36772. * @param source The source mesh that triggered the event
  36773. * @param evt {Event} The original (browser) event
  36774. */
  36775. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36776. var scene = source.getScene();
  36777. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36778. };
  36779. /**
  36780. * Helper function to auto-create an ActionEvent from a source mesh.
  36781. * @param source The source sprite that triggered the event
  36782. * @param scene Scene associated with the sprite
  36783. * @param evt {Event} The original (browser) event
  36784. */
  36785. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36786. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36787. };
  36788. /**
  36789. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36790. * @param scene the scene where the event occurred
  36791. * @param evt {Event} The original (browser) event
  36792. */
  36793. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36794. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36795. };
  36796. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36797. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36798. };
  36799. return ActionEvent;
  36800. }());
  36801. BABYLON.ActionEvent = ActionEvent;
  36802. /**
  36803. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36804. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36805. */
  36806. var ActionManager = (function () {
  36807. function ActionManager(scene) {
  36808. // Members
  36809. this.actions = new Array();
  36810. this.hoverCursor = '';
  36811. this._scene = scene;
  36812. scene._actionManagers.push(this);
  36813. }
  36814. Object.defineProperty(ActionManager, "NothingTrigger", {
  36815. get: function () {
  36816. return ActionManager._NothingTrigger;
  36817. },
  36818. enumerable: true,
  36819. configurable: true
  36820. });
  36821. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36822. get: function () {
  36823. return ActionManager._OnPickTrigger;
  36824. },
  36825. enumerable: true,
  36826. configurable: true
  36827. });
  36828. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36829. get: function () {
  36830. return ActionManager._OnLeftPickTrigger;
  36831. },
  36832. enumerable: true,
  36833. configurable: true
  36834. });
  36835. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36836. get: function () {
  36837. return ActionManager._OnRightPickTrigger;
  36838. },
  36839. enumerable: true,
  36840. configurable: true
  36841. });
  36842. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36843. get: function () {
  36844. return ActionManager._OnCenterPickTrigger;
  36845. },
  36846. enumerable: true,
  36847. configurable: true
  36848. });
  36849. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36850. get: function () {
  36851. return ActionManager._OnPickDownTrigger;
  36852. },
  36853. enumerable: true,
  36854. configurable: true
  36855. });
  36856. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  36857. get: function () {
  36858. return ActionManager._OnDoublePickTrigger;
  36859. },
  36860. enumerable: true,
  36861. configurable: true
  36862. });
  36863. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36864. get: function () {
  36865. return ActionManager._OnPickUpTrigger;
  36866. },
  36867. enumerable: true,
  36868. configurable: true
  36869. });
  36870. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36871. /// This trigger will only be raised if you also declared a OnPickDown
  36872. get: function () {
  36873. return ActionManager._OnPickOutTrigger;
  36874. },
  36875. enumerable: true,
  36876. configurable: true
  36877. });
  36878. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36879. get: function () {
  36880. return ActionManager._OnLongPressTrigger;
  36881. },
  36882. enumerable: true,
  36883. configurable: true
  36884. });
  36885. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36886. get: function () {
  36887. return ActionManager._OnPointerOverTrigger;
  36888. },
  36889. enumerable: true,
  36890. configurable: true
  36891. });
  36892. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36893. get: function () {
  36894. return ActionManager._OnPointerOutTrigger;
  36895. },
  36896. enumerable: true,
  36897. configurable: true
  36898. });
  36899. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36900. get: function () {
  36901. return ActionManager._OnEveryFrameTrigger;
  36902. },
  36903. enumerable: true,
  36904. configurable: true
  36905. });
  36906. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36907. get: function () {
  36908. return ActionManager._OnIntersectionEnterTrigger;
  36909. },
  36910. enumerable: true,
  36911. configurable: true
  36912. });
  36913. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36914. get: function () {
  36915. return ActionManager._OnIntersectionExitTrigger;
  36916. },
  36917. enumerable: true,
  36918. configurable: true
  36919. });
  36920. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36921. get: function () {
  36922. return ActionManager._OnKeyDownTrigger;
  36923. },
  36924. enumerable: true,
  36925. configurable: true
  36926. });
  36927. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36928. get: function () {
  36929. return ActionManager._OnKeyUpTrigger;
  36930. },
  36931. enumerable: true,
  36932. configurable: true
  36933. });
  36934. // Methods
  36935. ActionManager.prototype.dispose = function () {
  36936. var index = this._scene._actionManagers.indexOf(this);
  36937. for (var i = 0; i < this.actions.length; i++) {
  36938. var action = this.actions[i];
  36939. ActionManager.Triggers[action.trigger]--;
  36940. if (ActionManager.Triggers[action.trigger] === 0) {
  36941. delete ActionManager.Triggers[action.trigger];
  36942. }
  36943. }
  36944. if (index > -1) {
  36945. this._scene._actionManagers.splice(index, 1);
  36946. }
  36947. };
  36948. ActionManager.prototype.getScene = function () {
  36949. return this._scene;
  36950. };
  36951. /**
  36952. * Does this action manager handles actions of any of the given triggers
  36953. * @param {number[]} triggers - the triggers to be tested
  36954. * @return {boolean} whether one (or more) of the triggers is handeled
  36955. */
  36956. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36957. for (var index = 0; index < this.actions.length; index++) {
  36958. var action = this.actions[index];
  36959. if (triggers.indexOf(action.trigger) > -1) {
  36960. return true;
  36961. }
  36962. }
  36963. return false;
  36964. };
  36965. /**
  36966. * Does this action manager handles actions of a given trigger
  36967. * @param {number} trigger - the trigger to be tested
  36968. * @return {boolean} whether the trigger is handeled
  36969. */
  36970. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36971. for (var index = 0; index < this.actions.length; index++) {
  36972. var action = this.actions[index];
  36973. if (action.trigger === trigger) {
  36974. return true;
  36975. }
  36976. }
  36977. return false;
  36978. };
  36979. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36980. /**
  36981. * Does this action manager has pointer triggers
  36982. * @return {boolean} whether or not it has pointer triggers
  36983. */
  36984. get: function () {
  36985. for (var index = 0; index < this.actions.length; index++) {
  36986. var action = this.actions[index];
  36987. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36988. return true;
  36989. }
  36990. }
  36991. return false;
  36992. },
  36993. enumerable: true,
  36994. configurable: true
  36995. });
  36996. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36997. /**
  36998. * Does this action manager has pick triggers
  36999. * @return {boolean} whether or not it has pick triggers
  37000. */
  37001. get: function () {
  37002. for (var index = 0; index < this.actions.length; index++) {
  37003. var action = this.actions[index];
  37004. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  37005. return true;
  37006. }
  37007. }
  37008. return false;
  37009. },
  37010. enumerable: true,
  37011. configurable: true
  37012. });
  37013. Object.defineProperty(ActionManager, "HasTriggers", {
  37014. /**
  37015. * Does exist one action manager with at least one trigger
  37016. * @return {boolean} whether or not it exists one action manager with one trigger
  37017. **/
  37018. get: function () {
  37019. for (var t in ActionManager.Triggers) {
  37020. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37021. return true;
  37022. }
  37023. }
  37024. return false;
  37025. },
  37026. enumerable: true,
  37027. configurable: true
  37028. });
  37029. Object.defineProperty(ActionManager, "HasPickTriggers", {
  37030. /**
  37031. * Does exist one action manager with at least one pick trigger
  37032. * @return {boolean} whether or not it exists one action manager with one pick trigger
  37033. **/
  37034. get: function () {
  37035. for (var t in ActionManager.Triggers) {
  37036. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37037. var t_int = parseInt(t);
  37038. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  37039. return true;
  37040. }
  37041. }
  37042. }
  37043. return false;
  37044. },
  37045. enumerable: true,
  37046. configurable: true
  37047. });
  37048. /**
  37049. * Does exist one action manager that handles actions of a given trigger
  37050. * @param {number} trigger - the trigger to be tested
  37051. * @return {boolean} whether the trigger is handeled by at least one action manager
  37052. **/
  37053. ActionManager.HasSpecificTrigger = function (trigger) {
  37054. for (var t in ActionManager.Triggers) {
  37055. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37056. var t_int = parseInt(t);
  37057. if (t_int === trigger) {
  37058. return true;
  37059. }
  37060. }
  37061. }
  37062. return false;
  37063. };
  37064. /**
  37065. * Registers an action to this action manager
  37066. * @param {BABYLON.Action} action - the action to be registered
  37067. * @return {BABYLON.Action} the action amended (prepared) after registration
  37068. */
  37069. ActionManager.prototype.registerAction = function (action) {
  37070. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  37071. if (this.getScene().actionManager !== this) {
  37072. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  37073. return null;
  37074. }
  37075. }
  37076. this.actions.push(action);
  37077. if (ActionManager.Triggers[action.trigger]) {
  37078. ActionManager.Triggers[action.trigger]++;
  37079. }
  37080. else {
  37081. ActionManager.Triggers[action.trigger] = 1;
  37082. }
  37083. action._actionManager = this;
  37084. action._prepare();
  37085. return action;
  37086. };
  37087. /**
  37088. * Process a specific trigger
  37089. * @param {number} trigger - the trigger to process
  37090. * @param evt {BABYLON.ActionEvent} the event details to be processed
  37091. */
  37092. ActionManager.prototype.processTrigger = function (trigger, evt) {
  37093. for (var index = 0; index < this.actions.length; index++) {
  37094. var action = this.actions[index];
  37095. if (action.trigger === trigger) {
  37096. if (trigger === ActionManager.OnKeyUpTrigger
  37097. || trigger === ActionManager.OnKeyDownTrigger) {
  37098. var parameter = action.getTriggerParameter();
  37099. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  37100. if (!parameter.toLowerCase) {
  37101. continue;
  37102. }
  37103. var lowerCase = parameter.toLowerCase();
  37104. if (lowerCase !== evt.sourceEvent.key) {
  37105. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  37106. var actualkey = String.fromCharCode(unicode).toLowerCase();
  37107. if (actualkey !== lowerCase) {
  37108. continue;
  37109. }
  37110. }
  37111. }
  37112. }
  37113. action._executeCurrent(evt);
  37114. }
  37115. }
  37116. };
  37117. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  37118. var properties = propertyPath.split(".");
  37119. for (var index = 0; index < properties.length - 1; index++) {
  37120. target = target[properties[index]];
  37121. }
  37122. return target;
  37123. };
  37124. ActionManager.prototype._getProperty = function (propertyPath) {
  37125. var properties = propertyPath.split(".");
  37126. return properties[properties.length - 1];
  37127. };
  37128. ActionManager.prototype.serialize = function (name) {
  37129. var root = {
  37130. children: [],
  37131. name: name,
  37132. type: 3,
  37133. properties: [] // Empty for root but required
  37134. };
  37135. for (var i = 0; i < this.actions.length; i++) {
  37136. var triggerObject = {
  37137. type: 0,
  37138. children: [],
  37139. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  37140. properties: []
  37141. };
  37142. var triggerOptions = this.actions[i].triggerOptions;
  37143. if (triggerOptions && typeof triggerOptions !== "number") {
  37144. if (triggerOptions.parameter instanceof BABYLON.Node) {
  37145. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  37146. }
  37147. else {
  37148. var parameter = {};
  37149. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  37150. if (triggerOptions.parameter.mesh) {
  37151. parameter._meshId = triggerOptions.parameter.mesh.id;
  37152. }
  37153. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  37154. }
  37155. }
  37156. // Serialize child action, recursively
  37157. this.actions[i].serialize(triggerObject);
  37158. // Add serialized trigger
  37159. root.children.push(triggerObject);
  37160. }
  37161. return root;
  37162. };
  37163. ActionManager.Parse = function (parsedActions, object, scene) {
  37164. var actionManager = new BABYLON.ActionManager(scene);
  37165. if (object === null)
  37166. scene.actionManager = actionManager;
  37167. else
  37168. object.actionManager = actionManager;
  37169. // instanciate a new object
  37170. var instanciate = function (name, params) {
  37171. var newInstance = Object.create(BABYLON[name].prototype);
  37172. newInstance.constructor.apply(newInstance, params);
  37173. return newInstance;
  37174. };
  37175. var parseParameter = function (name, value, target, propertyPath) {
  37176. if (propertyPath === null) {
  37177. // String, boolean or float
  37178. var floatValue = parseFloat(value);
  37179. if (value === "true" || value === "false")
  37180. return value === "true";
  37181. else
  37182. return isNaN(floatValue) ? value : floatValue;
  37183. }
  37184. var effectiveTarget = propertyPath.split(".");
  37185. var values = value.split(",");
  37186. // Get effective Target
  37187. for (var i = 0; i < effectiveTarget.length; i++) {
  37188. target = target[effectiveTarget[i]];
  37189. }
  37190. // Return appropriate value with its type
  37191. if (typeof (target) === "boolean")
  37192. return values[0] === "true";
  37193. if (typeof (target) === "string")
  37194. return values[0];
  37195. // Parameters with multiple values such as Vector3 etc.
  37196. var split = new Array();
  37197. for (var i = 0; i < values.length; i++)
  37198. split.push(parseFloat(values[i]));
  37199. if (target instanceof BABYLON.Vector3)
  37200. return BABYLON.Vector3.FromArray(split);
  37201. if (target instanceof BABYLON.Vector4)
  37202. return BABYLON.Vector4.FromArray(split);
  37203. if (target instanceof BABYLON.Color3)
  37204. return BABYLON.Color3.FromArray(split);
  37205. if (target instanceof BABYLON.Color4)
  37206. return BABYLON.Color4.FromArray(split);
  37207. return parseFloat(values[0]);
  37208. };
  37209. // traverse graph per trigger
  37210. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  37211. if (combineArray === void 0) { combineArray = null; }
  37212. if (parsedAction.detached)
  37213. return;
  37214. var parameters = new Array();
  37215. var target = null;
  37216. var propertyPath = null;
  37217. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  37218. // Parameters
  37219. if (parsedAction.type === 2)
  37220. parameters.push(actionManager);
  37221. else
  37222. parameters.push(trigger);
  37223. if (combine) {
  37224. var actions = new Array();
  37225. for (var j = 0; j < parsedAction.combine.length; j++) {
  37226. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  37227. }
  37228. parameters.push(actions);
  37229. }
  37230. else {
  37231. for (var i = 0; i < parsedAction.properties.length; i++) {
  37232. var value = parsedAction.properties[i].value;
  37233. var name = parsedAction.properties[i].name;
  37234. var targetType = parsedAction.properties[i].targetType;
  37235. if (name === "target")
  37236. if (targetType !== null && targetType === "SceneProperties")
  37237. value = target = scene;
  37238. else
  37239. value = target = scene.getNodeByName(value);
  37240. else if (name === "parent")
  37241. value = scene.getNodeByName(value);
  37242. else if (name === "sound")
  37243. value = scene.getSoundByName(value);
  37244. else if (name !== "propertyPath") {
  37245. if (parsedAction.type === 2 && name === "operator")
  37246. value = BABYLON.ValueCondition[value];
  37247. else
  37248. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  37249. }
  37250. else {
  37251. propertyPath = value;
  37252. }
  37253. parameters.push(value);
  37254. }
  37255. }
  37256. if (combineArray === null) {
  37257. parameters.push(condition);
  37258. }
  37259. else {
  37260. parameters.push(null);
  37261. }
  37262. // If interpolate value action
  37263. if (parsedAction.name === "InterpolateValueAction") {
  37264. var param = parameters[parameters.length - 2];
  37265. parameters[parameters.length - 1] = param;
  37266. parameters[parameters.length - 2] = condition;
  37267. }
  37268. // Action or condition(s) and not CombineAction
  37269. var newAction = instanciate(parsedAction.name, parameters);
  37270. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37271. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37272. if (action)
  37273. action.then(nothing);
  37274. else
  37275. actionManager.registerAction(nothing);
  37276. action = nothing;
  37277. }
  37278. if (combineArray === null) {
  37279. if (newAction instanceof BABYLON.Condition) {
  37280. condition = newAction;
  37281. newAction = action;
  37282. }
  37283. else {
  37284. condition = null;
  37285. if (action)
  37286. action.then(newAction);
  37287. else
  37288. actionManager.registerAction(newAction);
  37289. }
  37290. }
  37291. else {
  37292. combineArray.push(newAction);
  37293. }
  37294. for (var i = 0; i < parsedAction.children.length; i++)
  37295. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37296. };
  37297. // triggers
  37298. for (var i = 0; i < parsedActions.children.length; i++) {
  37299. var triggerParams;
  37300. var trigger = parsedActions.children[i];
  37301. if (trigger.properties.length > 0) {
  37302. var param = trigger.properties[0].value;
  37303. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37304. if (value._meshId) {
  37305. value.mesh = scene.getMeshByID(value._meshId);
  37306. }
  37307. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37308. }
  37309. else
  37310. triggerParams = BABYLON.ActionManager[trigger.name];
  37311. for (var j = 0; j < trigger.children.length; j++) {
  37312. if (!trigger.detached)
  37313. traverse(trigger.children[j], triggerParams, null, null);
  37314. }
  37315. }
  37316. };
  37317. ActionManager.GetTriggerName = function (trigger) {
  37318. switch (trigger) {
  37319. case 0: return "NothingTrigger";
  37320. case 1: return "OnPickTrigger";
  37321. case 2: return "OnLeftPickTrigger";
  37322. case 3: return "OnRightPickTrigger";
  37323. case 4: return "OnCenterPickTrigger";
  37324. case 5: return "OnPickDownTrigger";
  37325. case 6: return "OnPickUpTrigger";
  37326. case 7: return "OnLongPressTrigger";
  37327. case 8: return "OnPointerOverTrigger";
  37328. case 9: return "OnPointerOutTrigger";
  37329. case 10: return "OnEveryFrameTrigger";
  37330. case 11: return "OnIntersectionEnterTrigger";
  37331. case 12: return "OnIntersectionExitTrigger";
  37332. case 13: return "OnKeyDownTrigger";
  37333. case 14: return "OnKeyUpTrigger";
  37334. case 15: return "OnPickOutTrigger";
  37335. default: return "";
  37336. }
  37337. };
  37338. return ActionManager;
  37339. }());
  37340. // Statics
  37341. ActionManager._NothingTrigger = 0;
  37342. ActionManager._OnPickTrigger = 1;
  37343. ActionManager._OnLeftPickTrigger = 2;
  37344. ActionManager._OnRightPickTrigger = 3;
  37345. ActionManager._OnCenterPickTrigger = 4;
  37346. ActionManager._OnPickDownTrigger = 5;
  37347. ActionManager._OnDoublePickTrigger = 6;
  37348. ActionManager._OnPickUpTrigger = 7;
  37349. ActionManager._OnLongPressTrigger = 8;
  37350. ActionManager._OnPointerOverTrigger = 9;
  37351. ActionManager._OnPointerOutTrigger = 10;
  37352. ActionManager._OnEveryFrameTrigger = 11;
  37353. ActionManager._OnIntersectionEnterTrigger = 12;
  37354. ActionManager._OnIntersectionExitTrigger = 13;
  37355. ActionManager._OnKeyDownTrigger = 14;
  37356. ActionManager._OnKeyUpTrigger = 15;
  37357. ActionManager._OnPickOutTrigger = 16;
  37358. ActionManager.Triggers = {};
  37359. BABYLON.ActionManager = ActionManager;
  37360. })(BABYLON || (BABYLON = {}));
  37361. //# sourceMappingURL=babylon.actionManager.js.map
  37362. var BABYLON;
  37363. (function (BABYLON) {
  37364. var InterpolateValueAction = (function (_super) {
  37365. __extends(InterpolateValueAction, _super);
  37366. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  37367. if (duration === void 0) { duration = 1000; }
  37368. var _this = _super.call(this, triggerOptions, condition) || this;
  37369. _this.propertyPath = propertyPath;
  37370. _this.value = value;
  37371. _this.duration = duration;
  37372. _this.stopOtherAnimations = stopOtherAnimations;
  37373. _this.onInterpolationDone = onInterpolationDone;
  37374. _this._target = _this._effectiveTarget = target;
  37375. return _this;
  37376. }
  37377. InterpolateValueAction.prototype._prepare = function () {
  37378. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37379. this._property = this._getProperty(this.propertyPath);
  37380. };
  37381. InterpolateValueAction.prototype.execute = function () {
  37382. var scene = this._actionManager.getScene();
  37383. var keys = [
  37384. {
  37385. frame: 0,
  37386. value: this._effectiveTarget[this._property]
  37387. }, {
  37388. frame: 100,
  37389. value: this.value
  37390. }
  37391. ];
  37392. var dataType;
  37393. if (typeof this.value === "number") {
  37394. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  37395. }
  37396. else if (this.value instanceof BABYLON.Color3) {
  37397. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  37398. }
  37399. else if (this.value instanceof BABYLON.Vector3) {
  37400. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  37401. }
  37402. else if (this.value instanceof BABYLON.Matrix) {
  37403. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  37404. }
  37405. else if (this.value instanceof BABYLON.Quaternion) {
  37406. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  37407. }
  37408. else {
  37409. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  37410. return;
  37411. }
  37412. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37413. animation.setKeys(keys);
  37414. if (this.stopOtherAnimations) {
  37415. scene.stopAnimation(this._effectiveTarget);
  37416. }
  37417. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  37418. };
  37419. InterpolateValueAction.prototype.serialize = function (parent) {
  37420. return _super.prototype._serialize.call(this, {
  37421. name: "InterpolateValueAction",
  37422. properties: [
  37423. BABYLON.Action._GetTargetProperty(this._target),
  37424. { name: "propertyPath", value: this.propertyPath },
  37425. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37426. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  37427. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  37428. ]
  37429. }, parent);
  37430. };
  37431. return InterpolateValueAction;
  37432. }(BABYLON.Action));
  37433. BABYLON.InterpolateValueAction = InterpolateValueAction;
  37434. })(BABYLON || (BABYLON = {}));
  37435. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  37436. var BABYLON;
  37437. (function (BABYLON) {
  37438. var SwitchBooleanAction = (function (_super) {
  37439. __extends(SwitchBooleanAction, _super);
  37440. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  37441. var _this = _super.call(this, triggerOptions, condition) || this;
  37442. _this.propertyPath = propertyPath;
  37443. _this._target = _this._effectiveTarget = target;
  37444. return _this;
  37445. }
  37446. SwitchBooleanAction.prototype._prepare = function () {
  37447. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37448. this._property = this._getProperty(this.propertyPath);
  37449. };
  37450. SwitchBooleanAction.prototype.execute = function () {
  37451. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  37452. };
  37453. SwitchBooleanAction.prototype.serialize = function (parent) {
  37454. return _super.prototype._serialize.call(this, {
  37455. name: "SwitchBooleanAction",
  37456. properties: [
  37457. BABYLON.Action._GetTargetProperty(this._target),
  37458. { name: "propertyPath", value: this.propertyPath }
  37459. ]
  37460. }, parent);
  37461. };
  37462. return SwitchBooleanAction;
  37463. }(BABYLON.Action));
  37464. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  37465. var SetStateAction = (function (_super) {
  37466. __extends(SetStateAction, _super);
  37467. function SetStateAction(triggerOptions, target, value, condition) {
  37468. var _this = _super.call(this, triggerOptions, condition) || this;
  37469. _this.value = value;
  37470. _this._target = target;
  37471. return _this;
  37472. }
  37473. SetStateAction.prototype.execute = function () {
  37474. this._target.state = this.value;
  37475. };
  37476. SetStateAction.prototype.serialize = function (parent) {
  37477. return _super.prototype._serialize.call(this, {
  37478. name: "SetStateAction",
  37479. properties: [
  37480. BABYLON.Action._GetTargetProperty(this._target),
  37481. { name: "value", value: this.value }
  37482. ]
  37483. }, parent);
  37484. };
  37485. return SetStateAction;
  37486. }(BABYLON.Action));
  37487. BABYLON.SetStateAction = SetStateAction;
  37488. var SetValueAction = (function (_super) {
  37489. __extends(SetValueAction, _super);
  37490. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  37491. var _this = _super.call(this, triggerOptions, condition) || this;
  37492. _this.propertyPath = propertyPath;
  37493. _this.value = value;
  37494. _this._target = _this._effectiveTarget = target;
  37495. return _this;
  37496. }
  37497. SetValueAction.prototype._prepare = function () {
  37498. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37499. this._property = this._getProperty(this.propertyPath);
  37500. };
  37501. SetValueAction.prototype.execute = function () {
  37502. this._effectiveTarget[this._property] = this.value;
  37503. if (this._target.markAsDirty) {
  37504. this._target.markAsDirty(this._property);
  37505. }
  37506. };
  37507. SetValueAction.prototype.serialize = function (parent) {
  37508. return _super.prototype._serialize.call(this, {
  37509. name: "SetValueAction",
  37510. properties: [
  37511. BABYLON.Action._GetTargetProperty(this._target),
  37512. { name: "propertyPath", value: this.propertyPath },
  37513. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37514. ]
  37515. }, parent);
  37516. };
  37517. return SetValueAction;
  37518. }(BABYLON.Action));
  37519. BABYLON.SetValueAction = SetValueAction;
  37520. var IncrementValueAction = (function (_super) {
  37521. __extends(IncrementValueAction, _super);
  37522. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37523. var _this = _super.call(this, triggerOptions, condition) || this;
  37524. _this.propertyPath = propertyPath;
  37525. _this.value = value;
  37526. _this._target = _this._effectiveTarget = target;
  37527. return _this;
  37528. }
  37529. IncrementValueAction.prototype._prepare = function () {
  37530. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37531. this._property = this._getProperty(this.propertyPath);
  37532. if (typeof this._effectiveTarget[this._property] !== "number") {
  37533. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37534. }
  37535. };
  37536. IncrementValueAction.prototype.execute = function () {
  37537. this._effectiveTarget[this._property] += this.value;
  37538. if (this._target.markAsDirty) {
  37539. this._target.markAsDirty(this._property);
  37540. }
  37541. };
  37542. IncrementValueAction.prototype.serialize = function (parent) {
  37543. return _super.prototype._serialize.call(this, {
  37544. name: "IncrementValueAction",
  37545. properties: [
  37546. BABYLON.Action._GetTargetProperty(this._target),
  37547. { name: "propertyPath", value: this.propertyPath },
  37548. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37549. ]
  37550. }, parent);
  37551. };
  37552. return IncrementValueAction;
  37553. }(BABYLON.Action));
  37554. BABYLON.IncrementValueAction = IncrementValueAction;
  37555. var PlayAnimationAction = (function (_super) {
  37556. __extends(PlayAnimationAction, _super);
  37557. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37558. var _this = _super.call(this, triggerOptions, condition) || this;
  37559. _this.from = from;
  37560. _this.to = to;
  37561. _this.loop = loop;
  37562. _this._target = target;
  37563. return _this;
  37564. }
  37565. PlayAnimationAction.prototype._prepare = function () {
  37566. };
  37567. PlayAnimationAction.prototype.execute = function () {
  37568. var scene = this._actionManager.getScene();
  37569. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37570. };
  37571. PlayAnimationAction.prototype.serialize = function (parent) {
  37572. return _super.prototype._serialize.call(this, {
  37573. name: "PlayAnimationAction",
  37574. properties: [
  37575. BABYLON.Action._GetTargetProperty(this._target),
  37576. { name: "from", value: String(this.from) },
  37577. { name: "to", value: String(this.to) },
  37578. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37579. ]
  37580. }, parent);
  37581. };
  37582. return PlayAnimationAction;
  37583. }(BABYLON.Action));
  37584. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37585. var StopAnimationAction = (function (_super) {
  37586. __extends(StopAnimationAction, _super);
  37587. function StopAnimationAction(triggerOptions, target, condition) {
  37588. var _this = _super.call(this, triggerOptions, condition) || this;
  37589. _this._target = target;
  37590. return _this;
  37591. }
  37592. StopAnimationAction.prototype._prepare = function () {
  37593. };
  37594. StopAnimationAction.prototype.execute = function () {
  37595. var scene = this._actionManager.getScene();
  37596. scene.stopAnimation(this._target);
  37597. };
  37598. StopAnimationAction.prototype.serialize = function (parent) {
  37599. return _super.prototype._serialize.call(this, {
  37600. name: "StopAnimationAction",
  37601. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  37602. }, parent);
  37603. };
  37604. return StopAnimationAction;
  37605. }(BABYLON.Action));
  37606. BABYLON.StopAnimationAction = StopAnimationAction;
  37607. var DoNothingAction = (function (_super) {
  37608. __extends(DoNothingAction, _super);
  37609. function DoNothingAction(triggerOptions, condition) {
  37610. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  37611. return _super.call(this, triggerOptions, condition) || this;
  37612. }
  37613. DoNothingAction.prototype.execute = function () {
  37614. };
  37615. DoNothingAction.prototype.serialize = function (parent) {
  37616. return _super.prototype._serialize.call(this, {
  37617. name: "DoNothingAction",
  37618. properties: []
  37619. }, parent);
  37620. };
  37621. return DoNothingAction;
  37622. }(BABYLON.Action));
  37623. BABYLON.DoNothingAction = DoNothingAction;
  37624. var CombineAction = (function (_super) {
  37625. __extends(CombineAction, _super);
  37626. function CombineAction(triggerOptions, children, condition) {
  37627. var _this = _super.call(this, triggerOptions, condition) || this;
  37628. _this.children = children;
  37629. return _this;
  37630. }
  37631. CombineAction.prototype._prepare = function () {
  37632. for (var index = 0; index < this.children.length; index++) {
  37633. this.children[index]._actionManager = this._actionManager;
  37634. this.children[index]._prepare();
  37635. }
  37636. };
  37637. CombineAction.prototype.execute = function (evt) {
  37638. for (var index = 0; index < this.children.length; index++) {
  37639. this.children[index].execute(evt);
  37640. }
  37641. };
  37642. CombineAction.prototype.serialize = function (parent) {
  37643. var serializationObject = _super.prototype._serialize.call(this, {
  37644. name: "CombineAction",
  37645. properties: [],
  37646. combine: []
  37647. }, parent);
  37648. for (var i = 0; i < this.children.length; i++) {
  37649. serializationObject.combine.push(this.children[i].serialize(null));
  37650. }
  37651. return serializationObject;
  37652. };
  37653. return CombineAction;
  37654. }(BABYLON.Action));
  37655. BABYLON.CombineAction = CombineAction;
  37656. var ExecuteCodeAction = (function (_super) {
  37657. __extends(ExecuteCodeAction, _super);
  37658. function ExecuteCodeAction(triggerOptions, func, condition) {
  37659. var _this = _super.call(this, triggerOptions, condition) || this;
  37660. _this.func = func;
  37661. return _this;
  37662. }
  37663. ExecuteCodeAction.prototype.execute = function (evt) {
  37664. this.func(evt);
  37665. };
  37666. return ExecuteCodeAction;
  37667. }(BABYLON.Action));
  37668. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37669. var SetParentAction = (function (_super) {
  37670. __extends(SetParentAction, _super);
  37671. function SetParentAction(triggerOptions, target, parent, condition) {
  37672. var _this = _super.call(this, triggerOptions, condition) || this;
  37673. _this._target = target;
  37674. _this._parent = parent;
  37675. return _this;
  37676. }
  37677. SetParentAction.prototype._prepare = function () {
  37678. };
  37679. SetParentAction.prototype.execute = function () {
  37680. if (this._target.parent === this._parent) {
  37681. return;
  37682. }
  37683. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37684. invertParentWorldMatrix.invert();
  37685. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37686. this._target.parent = this._parent;
  37687. };
  37688. SetParentAction.prototype.serialize = function (parent) {
  37689. return _super.prototype._serialize.call(this, {
  37690. name: "SetParentAction",
  37691. properties: [
  37692. BABYLON.Action._GetTargetProperty(this._target),
  37693. BABYLON.Action._GetTargetProperty(this._parent),
  37694. ]
  37695. }, parent);
  37696. };
  37697. return SetParentAction;
  37698. }(BABYLON.Action));
  37699. BABYLON.SetParentAction = SetParentAction;
  37700. var PlaySoundAction = (function (_super) {
  37701. __extends(PlaySoundAction, _super);
  37702. function PlaySoundAction(triggerOptions, sound, condition) {
  37703. var _this = _super.call(this, triggerOptions, condition) || this;
  37704. _this._sound = sound;
  37705. return _this;
  37706. }
  37707. PlaySoundAction.prototype._prepare = function () {
  37708. };
  37709. PlaySoundAction.prototype.execute = function () {
  37710. if (this._sound !== undefined)
  37711. this._sound.play();
  37712. };
  37713. PlaySoundAction.prototype.serialize = function (parent) {
  37714. return _super.prototype._serialize.call(this, {
  37715. name: "PlaySoundAction",
  37716. properties: [{ name: "sound", value: this._sound.name }]
  37717. }, parent);
  37718. };
  37719. return PlaySoundAction;
  37720. }(BABYLON.Action));
  37721. BABYLON.PlaySoundAction = PlaySoundAction;
  37722. var StopSoundAction = (function (_super) {
  37723. __extends(StopSoundAction, _super);
  37724. function StopSoundAction(triggerOptions, sound, condition) {
  37725. var _this = _super.call(this, triggerOptions, condition) || this;
  37726. _this._sound = sound;
  37727. return _this;
  37728. }
  37729. StopSoundAction.prototype._prepare = function () {
  37730. };
  37731. StopSoundAction.prototype.execute = function () {
  37732. if (this._sound !== undefined)
  37733. this._sound.stop();
  37734. };
  37735. StopSoundAction.prototype.serialize = function (parent) {
  37736. return _super.prototype._serialize.call(this, {
  37737. name: "StopSoundAction",
  37738. properties: [{ name: "sound", value: this._sound.name }]
  37739. }, parent);
  37740. };
  37741. return StopSoundAction;
  37742. }(BABYLON.Action));
  37743. BABYLON.StopSoundAction = StopSoundAction;
  37744. })(BABYLON || (BABYLON = {}));
  37745. //# sourceMappingURL=babylon.directActions.js.map
  37746. var BABYLON;
  37747. (function (BABYLON) {
  37748. var Debug;
  37749. (function (Debug) {
  37750. /**
  37751. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  37752. */
  37753. var SkeletonViewer = (function () {
  37754. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  37755. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  37756. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  37757. this.skeleton = skeleton;
  37758. this.mesh = mesh;
  37759. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  37760. this.renderingGroupId = renderingGroupId;
  37761. this.color = BABYLON.Color3.White();
  37762. this._debugLines = [];
  37763. this._isEnabled = false;
  37764. this._scene = scene;
  37765. this.update();
  37766. this._renderFunction = this.update.bind(this);
  37767. }
  37768. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  37769. get: function () {
  37770. return this._isEnabled;
  37771. },
  37772. set: function (value) {
  37773. if (this._isEnabled === value) {
  37774. return;
  37775. }
  37776. this._isEnabled = value;
  37777. if (value) {
  37778. this._scene.registerBeforeRender(this._renderFunction);
  37779. }
  37780. else {
  37781. this._scene.unregisterBeforeRender(this._renderFunction);
  37782. }
  37783. },
  37784. enumerable: true,
  37785. configurable: true
  37786. });
  37787. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  37788. if (x === void 0) { x = 0; }
  37789. if (y === void 0) { y = 0; }
  37790. if (z === void 0) { z = 0; }
  37791. var tmat = BABYLON.Tmp.Matrix[0];
  37792. var parentBone = bone.getParent();
  37793. tmat.copyFrom(bone.getLocalMatrix());
  37794. if (x !== 0 || y !== 0 || z !== 0) {
  37795. var tmat2 = BABYLON.Tmp.Matrix[1];
  37796. BABYLON.Matrix.IdentityToRef(tmat2);
  37797. tmat2.m[12] = x;
  37798. tmat2.m[13] = y;
  37799. tmat2.m[14] = z;
  37800. tmat2.multiplyToRef(tmat, tmat);
  37801. }
  37802. if (parentBone) {
  37803. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  37804. }
  37805. tmat.multiplyToRef(meshMat, tmat);
  37806. position.x = tmat.m[12];
  37807. position.y = tmat.m[13];
  37808. position.z = tmat.m[14];
  37809. };
  37810. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  37811. var len = bones.length;
  37812. var meshPos = this.mesh.position;
  37813. for (var i = 0; i < len; i++) {
  37814. var bone = bones[i];
  37815. var points = this._debugLines[i];
  37816. if (!points) {
  37817. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37818. this._debugLines[i] = points;
  37819. }
  37820. this._getBonePosition(points[0], bone, meshMat);
  37821. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  37822. points[0].subtractInPlace(meshPos);
  37823. points[1].subtractInPlace(meshPos);
  37824. }
  37825. };
  37826. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  37827. var len = bones.length;
  37828. var boneNum = 0;
  37829. var meshPos = this.mesh.position;
  37830. for (var i = len - 1; i >= 0; i--) {
  37831. var childBone = bones[i];
  37832. var parentBone = childBone.getParent();
  37833. if (!parentBone) {
  37834. continue;
  37835. }
  37836. var points = this._debugLines[boneNum];
  37837. if (!points) {
  37838. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37839. this._debugLines[boneNum] = points;
  37840. }
  37841. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  37842. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  37843. points[0].subtractInPlace(meshPos);
  37844. points[1].subtractInPlace(meshPos);
  37845. boneNum++;
  37846. }
  37847. };
  37848. SkeletonViewer.prototype.update = function () {
  37849. if (this.autoUpdateBonesMatrices) {
  37850. this.skeleton.computeAbsoluteTransforms();
  37851. }
  37852. if (this.skeleton.bones[0].length === undefined) {
  37853. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37854. }
  37855. else {
  37856. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37857. }
  37858. if (!this._debugMesh) {
  37859. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  37860. this._debugMesh.renderingGroupId = this.renderingGroupId;
  37861. }
  37862. else {
  37863. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  37864. }
  37865. this._debugMesh.position.copyFrom(this.mesh.position);
  37866. this._debugMesh.color = this.color;
  37867. };
  37868. SkeletonViewer.prototype.dispose = function () {
  37869. if (this._debugMesh) {
  37870. this.isEnabled = false;
  37871. this._debugMesh.dispose();
  37872. this._debugMesh = null;
  37873. }
  37874. };
  37875. return SkeletonViewer;
  37876. }());
  37877. Debug.SkeletonViewer = SkeletonViewer;
  37878. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37879. })(BABYLON || (BABYLON = {}));
  37880. //# sourceMappingURL=babylon.skeletonViewer.js.map
  37881. var BABYLON;
  37882. (function (BABYLON) {
  37883. var Debug;
  37884. (function (Debug) {
  37885. var AxesViewer = (function () {
  37886. function AxesViewer(scene, scaleLines) {
  37887. if (scaleLines === void 0) { scaleLines = 1; }
  37888. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37889. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37890. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37891. this.scaleLines = 1;
  37892. this.scaleLines = scaleLines;
  37893. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  37894. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  37895. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  37896. this._xmesh.renderingGroupId = 2;
  37897. this._ymesh.renderingGroupId = 2;
  37898. this._zmesh.renderingGroupId = 2;
  37899. this._xmesh.material.checkReadyOnlyOnce = true;
  37900. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  37901. this._ymesh.material.checkReadyOnlyOnce = true;
  37902. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  37903. this._zmesh.material.checkReadyOnlyOnce = true;
  37904. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  37905. this.scene = scene;
  37906. }
  37907. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  37908. var scaleLines = this.scaleLines;
  37909. this._xmesh.position.copyFrom(position);
  37910. this._ymesh.position.copyFrom(position);
  37911. this._zmesh.position.copyFrom(position);
  37912. var point2 = this._xline[1];
  37913. point2.x = xaxis.x * scaleLines;
  37914. point2.y = xaxis.y * scaleLines;
  37915. point2.z = xaxis.z * scaleLines;
  37916. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  37917. point2 = this._yline[1];
  37918. point2.x = yaxis.x * scaleLines;
  37919. point2.y = yaxis.y * scaleLines;
  37920. point2.z = yaxis.z * scaleLines;
  37921. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  37922. point2 = this._zline[1];
  37923. point2.x = zaxis.x * scaleLines;
  37924. point2.y = zaxis.y * scaleLines;
  37925. point2.z = zaxis.z * scaleLines;
  37926. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  37927. };
  37928. AxesViewer.prototype.dispose = function () {
  37929. if (this._xmesh) {
  37930. this._xmesh.dispose();
  37931. this._ymesh.dispose();
  37932. this._zmesh.dispose();
  37933. this._xmesh = null;
  37934. this._ymesh = null;
  37935. this._zmesh = null;
  37936. this._xline = null;
  37937. this._yline = null;
  37938. this._zline = null;
  37939. this.scene = null;
  37940. }
  37941. };
  37942. return AxesViewer;
  37943. }());
  37944. Debug.AxesViewer = AxesViewer;
  37945. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37946. })(BABYLON || (BABYLON = {}));
  37947. //# sourceMappingURL=babylon.axesViewer.js.map
  37948. var BABYLON;
  37949. (function (BABYLON) {
  37950. var Debug;
  37951. (function (Debug) {
  37952. var BoneAxesViewer = (function (_super) {
  37953. __extends(BoneAxesViewer, _super);
  37954. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  37955. if (scaleLines === void 0) { scaleLines = 1; }
  37956. var _this = _super.call(this, scene, scaleLines) || this;
  37957. _this.pos = BABYLON.Vector3.Zero();
  37958. _this.xaxis = BABYLON.Vector3.Zero();
  37959. _this.yaxis = BABYLON.Vector3.Zero();
  37960. _this.zaxis = BABYLON.Vector3.Zero();
  37961. _this.mesh = mesh;
  37962. _this.bone = bone;
  37963. return _this;
  37964. }
  37965. BoneAxesViewer.prototype.update = function () {
  37966. var bone = this.bone;
  37967. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  37968. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  37969. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  37970. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  37971. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  37972. };
  37973. BoneAxesViewer.prototype.dispose = function () {
  37974. if (this.pos) {
  37975. this.pos = null;
  37976. this.xaxis = null;
  37977. this.yaxis = null;
  37978. this.zaxis = null;
  37979. this.mesh = null;
  37980. this.bone = null;
  37981. _super.prototype.dispose.call(this);
  37982. }
  37983. };
  37984. return BoneAxesViewer;
  37985. }(Debug.AxesViewer));
  37986. Debug.BoneAxesViewer = BoneAxesViewer;
  37987. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37988. })(BABYLON || (BABYLON = {}));
  37989. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  37990. var BABYLON;
  37991. (function (BABYLON) {
  37992. var RayHelper = (function () {
  37993. function RayHelper(ray) {
  37994. this.ray = ray;
  37995. }
  37996. RayHelper.CreateAndShow = function (ray, scene, color) {
  37997. var helper = new RayHelper(ray);
  37998. helper.show(scene, color);
  37999. return helper;
  38000. };
  38001. RayHelper.prototype.show = function (scene, color) {
  38002. if (!this._renderFunction) {
  38003. var ray = this.ray;
  38004. this._renderFunction = this._render.bind(this);
  38005. this._scene = scene;
  38006. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  38007. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  38008. this._scene.registerBeforeRender(this._renderFunction);
  38009. }
  38010. if (color) {
  38011. this._renderLine.color.copyFrom(color);
  38012. }
  38013. };
  38014. RayHelper.prototype.hide = function () {
  38015. if (this._renderFunction) {
  38016. this._scene.unregisterBeforeRender(this._renderFunction);
  38017. this._scene = null;
  38018. this._renderFunction = null;
  38019. this._renderLine.dispose();
  38020. this._renderLine = null;
  38021. this._renderPoints = null;
  38022. }
  38023. };
  38024. RayHelper.prototype._render = function () {
  38025. var ray = this.ray;
  38026. var point = this._renderPoints[1];
  38027. var len = Math.min(ray.length, 1000000);
  38028. point.copyFrom(ray.direction);
  38029. point.scaleInPlace(len);
  38030. point.addInPlace(ray.origin);
  38031. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  38032. };
  38033. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  38034. this._attachedToMesh = mesh;
  38035. var ray = this.ray;
  38036. if (!ray.direction) {
  38037. ray.direction = BABYLON.Vector3.Zero();
  38038. }
  38039. if (!ray.origin) {
  38040. ray.origin = BABYLON.Vector3.Zero();
  38041. }
  38042. if (length) {
  38043. ray.length = length;
  38044. }
  38045. if (!meshSpaceOrigin) {
  38046. meshSpaceOrigin = BABYLON.Vector3.Zero();
  38047. }
  38048. if (!meshSpaceDirection) {
  38049. // -1 so that this will work with Mesh.lookAt
  38050. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  38051. }
  38052. if (!this._meshSpaceDirection) {
  38053. this._meshSpaceDirection = meshSpaceDirection.clone();
  38054. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  38055. }
  38056. else {
  38057. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  38058. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  38059. }
  38060. if (!this._updateToMeshFunction) {
  38061. this._updateToMeshFunction = this._updateToMesh.bind(this);
  38062. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  38063. }
  38064. this._updateToMesh();
  38065. };
  38066. RayHelper.prototype.detachFromMesh = function () {
  38067. if (this._attachedToMesh) {
  38068. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  38069. this._attachedToMesh = null;
  38070. this._updateToMeshFunction = null;
  38071. }
  38072. };
  38073. RayHelper.prototype._updateToMesh = function () {
  38074. var ray = this.ray;
  38075. if (this._attachedToMesh._isDisposed) {
  38076. this.detachFromMesh();
  38077. return;
  38078. }
  38079. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  38080. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  38081. };
  38082. RayHelper.prototype.dispose = function () {
  38083. this.hide();
  38084. this.detachFromMesh();
  38085. this.ray = null;
  38086. };
  38087. return RayHelper;
  38088. }());
  38089. BABYLON.RayHelper = RayHelper;
  38090. })(BABYLON || (BABYLON = {}));
  38091. //# sourceMappingURL=babylon.rayHelper.js.map
  38092. var BABYLON;
  38093. (function (BABYLON) {
  38094. var DebugLayer = (function () {
  38095. function DebugLayer(scene) {
  38096. this._scene = scene;
  38097. }
  38098. /** Creates the inspector window. */
  38099. DebugLayer.prototype._createInspector = function (config) {
  38100. if (config === void 0) { config = {}; }
  38101. var popup = config.popup || false;
  38102. var initialTab = config.initialTab || 0;
  38103. var parentElement = config.parentElement || null;
  38104. if (!this._inspector) {
  38105. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  38106. } // else nothing to do,; instance is already existing
  38107. };
  38108. DebugLayer.prototype.isVisible = function () {
  38109. if (!this._inspector) {
  38110. return false;
  38111. }
  38112. return true;
  38113. };
  38114. DebugLayer.prototype.hide = function () {
  38115. if (this._inspector) {
  38116. try {
  38117. this._inspector.dispose();
  38118. }
  38119. catch (e) {
  38120. // If the inspector has been removed directly from the inspector tool
  38121. }
  38122. this._inspector = null;
  38123. }
  38124. };
  38125. DebugLayer.prototype.show = function (config) {
  38126. if (config === void 0) { config = {}; }
  38127. if (typeof INSPECTOR == 'undefined') {
  38128. // Load inspector and add it to the DOM
  38129. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  38130. }
  38131. else {
  38132. // Otherwise creates the inspector
  38133. this._createInspector(config);
  38134. }
  38135. };
  38136. return DebugLayer;
  38137. }());
  38138. // Get protocol used - http or https
  38139. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  38140. BABYLON.DebugLayer = DebugLayer;
  38141. })(BABYLON || (BABYLON = {}));
  38142. //# sourceMappingURL=babylon.debugLayer.js.map
  38143. var BABYLON;
  38144. (function (BABYLON) {
  38145. var BoundingBoxRenderer = (function () {
  38146. function BoundingBoxRenderer(scene) {
  38147. this.frontColor = new BABYLON.Color3(1, 1, 1);
  38148. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  38149. this.showBackLines = true;
  38150. this.renderList = new BABYLON.SmartArray(32);
  38151. this._vertexBuffers = {};
  38152. this._scene = scene;
  38153. }
  38154. BoundingBoxRenderer.prototype._prepareRessources = function () {
  38155. if (this._colorShader) {
  38156. return;
  38157. }
  38158. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  38159. attributes: [BABYLON.VertexBuffer.PositionKind],
  38160. uniforms: ["world", "viewProjection", "color"]
  38161. });
  38162. var engine = this._scene.getEngine();
  38163. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  38164. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  38165. 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]);
  38166. };
  38167. BoundingBoxRenderer.prototype.reset = function () {
  38168. this.renderList.reset();
  38169. };
  38170. BoundingBoxRenderer.prototype.render = function () {
  38171. if (this.renderList.length === 0) {
  38172. return;
  38173. }
  38174. this._prepareRessources();
  38175. if (!this._colorShader.isReady()) {
  38176. return;
  38177. }
  38178. var engine = this._scene.getEngine();
  38179. engine.setDepthWrite(false);
  38180. this._colorShader._preBind();
  38181. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  38182. var boundingBox = this.renderList.data[boundingBoxIndex];
  38183. var min = boundingBox.minimum;
  38184. var max = boundingBox.maximum;
  38185. var diff = max.subtract(min);
  38186. var median = min.add(diff.scale(0.5));
  38187. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  38188. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  38189. .multiply(boundingBox.getWorldMatrix());
  38190. // VBOs
  38191. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  38192. if (this.showBackLines) {
  38193. // Back
  38194. engine.setDepthFunctionToGreaterOrEqual();
  38195. this._scene.resetCachedMaterial();
  38196. this._colorShader.setColor4("color", this.backColor.toColor4());
  38197. this._colorShader.bind(worldMatrix);
  38198. // Draw order
  38199. engine.draw(false, 0, 24);
  38200. }
  38201. // Front
  38202. engine.setDepthFunctionToLess();
  38203. this._scene.resetCachedMaterial();
  38204. this._colorShader.setColor4("color", this.frontColor.toColor4());
  38205. this._colorShader.bind(worldMatrix);
  38206. // Draw order
  38207. engine.draw(false, 0, 24);
  38208. }
  38209. this._colorShader.unbind();
  38210. engine.setDepthFunctionToLessOrEqual();
  38211. engine.setDepthWrite(true);
  38212. };
  38213. BoundingBoxRenderer.prototype.dispose = function () {
  38214. if (!this._colorShader) {
  38215. return;
  38216. }
  38217. this.renderList.dispose();
  38218. this._colorShader.dispose();
  38219. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38220. if (buffer) {
  38221. buffer.dispose();
  38222. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38223. }
  38224. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38225. };
  38226. return BoundingBoxRenderer;
  38227. }());
  38228. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  38229. })(BABYLON || (BABYLON = {}));
  38230. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  38231. var BABYLON;
  38232. (function (BABYLON) {
  38233. var MultiMaterial = (function (_super) {
  38234. __extends(MultiMaterial, _super);
  38235. function MultiMaterial(name, scene) {
  38236. var _this = _super.call(this, name, scene, true) || this;
  38237. _this.subMaterials = new Array();
  38238. scene.multiMaterials.push(_this);
  38239. return _this;
  38240. }
  38241. // Properties
  38242. MultiMaterial.prototype.getSubMaterial = function (index) {
  38243. if (index < 0 || index >= this.subMaterials.length) {
  38244. return this.getScene().defaultMaterial;
  38245. }
  38246. return this.subMaterials[index];
  38247. };
  38248. // Methods
  38249. MultiMaterial.prototype.getClassName = function () {
  38250. return "MultiMaterial";
  38251. };
  38252. MultiMaterial.prototype.isReady = function (mesh) {
  38253. for (var index = 0; index < this.subMaterials.length; index++) {
  38254. var subMaterial = this.subMaterials[index];
  38255. if (subMaterial) {
  38256. if (!this.subMaterials[index].isReady(mesh)) {
  38257. return false;
  38258. }
  38259. }
  38260. }
  38261. return true;
  38262. };
  38263. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  38264. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  38265. for (var index = 0; index < this.subMaterials.length; index++) {
  38266. var subMaterial = null;
  38267. if (cloneChildren) {
  38268. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  38269. }
  38270. else {
  38271. subMaterial = this.subMaterials[index];
  38272. }
  38273. newMultiMaterial.subMaterials.push(subMaterial);
  38274. }
  38275. return newMultiMaterial;
  38276. };
  38277. MultiMaterial.prototype.serialize = function () {
  38278. var serializationObject = {};
  38279. serializationObject.name = this.name;
  38280. serializationObject.id = this.id;
  38281. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38282. serializationObject.materials = [];
  38283. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  38284. var subMat = this.subMaterials[matIndex];
  38285. if (subMat) {
  38286. serializationObject.materials.push(subMat.id);
  38287. }
  38288. else {
  38289. serializationObject.materials.push(null);
  38290. }
  38291. }
  38292. return serializationObject;
  38293. };
  38294. return MultiMaterial;
  38295. }(BABYLON.Material));
  38296. BABYLON.MultiMaterial = MultiMaterial;
  38297. })(BABYLON || (BABYLON = {}));
  38298. //# sourceMappingURL=babylon.multiMaterial.js.map
  38299. var BABYLON;
  38300. (function (BABYLON) {
  38301. var PBRMaterialDefines = (function (_super) {
  38302. __extends(PBRMaterialDefines, _super);
  38303. function PBRMaterialDefines() {
  38304. var _this = _super.call(this) || this;
  38305. _this.PBR = true;
  38306. _this.ALBEDO = false;
  38307. _this.AMBIENT = false;
  38308. _this.AMBIENTINGRAYSCALE = false;
  38309. _this.OPACITY = false;
  38310. _this.OPACITYRGB = false;
  38311. _this.REFLECTION = false;
  38312. _this.EMISSIVE = false;
  38313. _this.REFLECTIVITY = false;
  38314. _this.BUMP = false;
  38315. _this.PARALLAX = false;
  38316. _this.PARALLAXOCCLUSION = false;
  38317. _this.SPECULAROVERALPHA = false;
  38318. _this.CLIPPLANE = false;
  38319. _this.ALPHATEST = false;
  38320. _this.ALPHAFROMALBEDO = false;
  38321. _this.POINTSIZE = false;
  38322. _this.FOG = false;
  38323. _this.SPECULARTERM = false;
  38324. _this.OPACITYFRESNEL = false;
  38325. _this.EMISSIVEFRESNEL = false;
  38326. _this.FRESNEL = false;
  38327. _this.NORMAL = false;
  38328. _this.TANGENT = false;
  38329. _this.UV1 = false;
  38330. _this.UV2 = false;
  38331. _this.VERTEXCOLOR = false;
  38332. _this.VERTEXALPHA = false;
  38333. _this.NUM_BONE_INFLUENCERS = 0;
  38334. _this.BonesPerMesh = 0;
  38335. _this.INSTANCES = false;
  38336. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38337. _this.MICROSURFACEAUTOMATIC = false;
  38338. _this.EMISSIVEASILLUMINATION = false;
  38339. _this.LIGHTMAP = false;
  38340. _this.USELIGHTMAPASSHADOWMAP = false;
  38341. _this.REFLECTIONMAP_3D = false;
  38342. _this.REFLECTIONMAP_SPHERICAL = false;
  38343. _this.REFLECTIONMAP_PLANAR = false;
  38344. _this.REFLECTIONMAP_CUBIC = false;
  38345. _this.REFLECTIONMAP_PROJECTION = false;
  38346. _this.REFLECTIONMAP_SKYBOX = false;
  38347. _this.REFLECTIONMAP_EXPLICIT = false;
  38348. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38349. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38350. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38351. _this.INVERTCUBICMAP = false;
  38352. _this.LOGARITHMICDEPTH = false;
  38353. _this.CAMERATONEMAP = false;
  38354. _this.CAMERACONTRAST = false;
  38355. _this.CAMERACOLORGRADING = false;
  38356. _this.CAMERACOLORCURVES = false;
  38357. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38358. _this.REFRACTION = false;
  38359. _this.REFRACTIONMAP_3D = false;
  38360. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38361. _this.REFRACTIONMAPINLINEARSPACE = false;
  38362. _this.LODBASEDMICROSFURACE = false;
  38363. _this.USEPHYSICALLIGHTFALLOFF = false;
  38364. _this.RADIANCEOVERALPHA = false;
  38365. _this.USEPMREMREFLECTION = false;
  38366. _this.USEPMREMREFRACTION = false;
  38367. _this.INVERTNORMALMAPX = false;
  38368. _this.INVERTNORMALMAPY = false;
  38369. _this.TWOSIDEDLIGHTING = false;
  38370. _this.SHADOWFLOAT = false;
  38371. _this.NORMALXYSCALE = true;
  38372. _this.USERIGHTHANDEDSYSTEM = false;
  38373. _this.METALLICWORKFLOW = false;
  38374. _this.METALLICMAP = false;
  38375. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38376. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38377. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38378. _this.AOSTOREINMETALMAPRED = false;
  38379. _this.MICROSURFACEMAP = false;
  38380. _this.MORPHTARGETS = false;
  38381. _this.MORPHTARGETS_NORMAL = false;
  38382. _this.MORPHTARGETS_TANGENT = false;
  38383. _this.NUM_MORPH_INFLUENCERS = 0;
  38384. _this.ALPHATESTVALUE = 0.4;
  38385. _this.LDROUTPUT = true;
  38386. _this.rebuild();
  38387. return _this;
  38388. }
  38389. PBRMaterialDefines.prototype.reset = function () {
  38390. _super.prototype.reset.call(this);
  38391. this.ALPHATESTVALUE = 0.4;
  38392. this.PBR = true;
  38393. };
  38394. return PBRMaterialDefines;
  38395. }(BABYLON.MaterialDefines));
  38396. /**
  38397. * The Physically based material base class of BJS.
  38398. *
  38399. * This offers the main features of a standard PBR material.
  38400. * For more information, please refer to the documentation :
  38401. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38402. */
  38403. var PBRBaseMaterial = (function (_super) {
  38404. __extends(PBRBaseMaterial, _super);
  38405. /**
  38406. * Instantiates a new PBRMaterial instance.
  38407. *
  38408. * @param name The material name
  38409. * @param scene The scene the material will be use in.
  38410. */
  38411. function PBRBaseMaterial(name, scene) {
  38412. var _this = _super.call(this, name, scene) || this;
  38413. /**
  38414. * Intensity of the direct lights e.g. the four lights available in your scene.
  38415. * This impacts both the direct diffuse and specular highlights.
  38416. */
  38417. _this._directIntensity = 1.0;
  38418. /**
  38419. * Intensity of the emissive part of the material.
  38420. * This helps controlling the emissive effect without modifying the emissive color.
  38421. */
  38422. _this._emissiveIntensity = 1.0;
  38423. /**
  38424. * Intensity of the environment e.g. how much the environment will light the object
  38425. * either through harmonics for rough material or through the refelction for shiny ones.
  38426. */
  38427. _this._environmentIntensity = 1.0;
  38428. /**
  38429. * This is a special control allowing the reduction of the specular highlights coming from the
  38430. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38431. */
  38432. _this._specularIntensity = 1.0;
  38433. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38434. /**
  38435. * Debug Control allowing disabling the bump map on this material.
  38436. */
  38437. _this._disableBumpMap = false;
  38438. /**
  38439. * The camera exposure used on this material.
  38440. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38441. * This corresponds to a photographic exposure.
  38442. */
  38443. _this._cameraExposure = 1.0;
  38444. /**
  38445. * The camera contrast used on this material.
  38446. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  38447. */
  38448. _this._cameraContrast = 1.0;
  38449. /**
  38450. * Color Grading 2D Lookup Texture.
  38451. * This allows special effects like sepia, black and white to sixties rendering style.
  38452. */
  38453. _this._cameraColorGradingTexture = null;
  38454. /**
  38455. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38456. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38457. * 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;
  38458. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38459. */
  38460. _this._cameraColorCurves = null;
  38461. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  38462. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  38463. /**
  38464. * AKA Occlusion Texture Intensity in other nomenclature.
  38465. */
  38466. _this._ambientTextureStrength = 1.0;
  38467. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38468. /**
  38469. * AKA Diffuse Color in other nomenclature.
  38470. */
  38471. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38472. /**
  38473. * AKA Specular Color in other nomenclature.
  38474. */
  38475. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38476. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  38477. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38478. /**
  38479. * AKA Glossiness in other nomenclature.
  38480. */
  38481. _this._microSurface = 0.9;
  38482. /**
  38483. * source material index of refraction (IOR)' / 'destination material IOR.
  38484. */
  38485. _this._indexOfRefraction = 0.66;
  38486. /**
  38487. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38488. */
  38489. _this._invertRefractionY = false;
  38490. /**
  38491. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38492. * Materials half opaque for instance using refraction could benefit from this control.
  38493. */
  38494. _this._linkRefractionWithTransparency = false;
  38495. _this._useLightmapAsShadowmap = false;
  38496. /**
  38497. * In this mode, the emissive informtaion will always be added to the lighting once.
  38498. * A light for instance can be thought as emissive.
  38499. */
  38500. _this._useEmissiveAsIllumination = false;
  38501. /**
  38502. * Secifies that the alpha is coming form the albedo channel alpha channel.
  38503. */
  38504. _this._useAlphaFromAlbedoTexture = false;
  38505. /**
  38506. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38507. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38508. */
  38509. _this._useSpecularOverAlpha = true;
  38510. /**
  38511. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38512. */
  38513. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38514. /**
  38515. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38516. */
  38517. _this._useRoughnessFromMetallicTextureAlpha = true;
  38518. /**
  38519. * Specifies if the metallic texture contains the roughness information in its green channel.
  38520. */
  38521. _this._useRoughnessFromMetallicTextureGreen = false;
  38522. /**
  38523. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38524. */
  38525. _this._useMetallnessFromMetallicTextureBlue = false;
  38526. /**
  38527. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38528. */
  38529. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38530. /**
  38531. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38532. */
  38533. _this._useAmbientInGrayScale = false;
  38534. /**
  38535. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38536. * The material will try to infer what glossiness each pixel should be.
  38537. */
  38538. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38539. /**
  38540. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  38541. * the creation of the material.
  38542. */
  38543. _this._useScalarInLinearSpace = false;
  38544. /**
  38545. * BJS is using an harcoded light falloff based on a manually sets up range.
  38546. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38547. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38548. */
  38549. _this._usePhysicalLightFalloff = true;
  38550. /**
  38551. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38552. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38553. */
  38554. _this._useRadianceOverAlpha = true;
  38555. /**
  38556. * Allows using the bump map in parallax mode.
  38557. */
  38558. _this._useParallax = false;
  38559. /**
  38560. * Allows using the bump map in parallax occlusion mode.
  38561. */
  38562. _this._useParallaxOcclusion = false;
  38563. /**
  38564. * Controls the scale bias of the parallax mode.
  38565. */
  38566. _this._parallaxScaleBias = 0.05;
  38567. /**
  38568. * If sets to true, disables all the lights affecting the material.
  38569. */
  38570. _this._disableLighting = false;
  38571. /**
  38572. * Number of Simultaneous lights allowed on the material.
  38573. */
  38574. _this._maxSimultaneousLights = 4;
  38575. /**
  38576. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38577. */
  38578. _this._invertNormalMapX = false;
  38579. /**
  38580. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38581. */
  38582. _this._invertNormalMapY = false;
  38583. /**
  38584. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38585. */
  38586. _this._twoSidedLighting = false;
  38587. /**
  38588. * Defines the alpha limits in alpha test mode.
  38589. */
  38590. _this._alphaCutOff = 0.4;
  38591. /**
  38592. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38593. */
  38594. _this._forceAlphaTest = false;
  38595. /**
  38596. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is useful
  38597. * in combination of post process in float or half float mode.
  38598. */
  38599. _this._ldrOutput = true;
  38600. _this._renderTargets = new BABYLON.SmartArray(16);
  38601. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38602. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38603. _this._tempColor = new BABYLON.Color3();
  38604. _this.getRenderTargetTextures = function () {
  38605. _this._renderTargets.reset();
  38606. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38607. _this._renderTargets.push(_this._reflectionTexture);
  38608. }
  38609. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38610. _this._renderTargets.push(_this._refractionTexture);
  38611. }
  38612. return _this._renderTargets;
  38613. };
  38614. return _this;
  38615. }
  38616. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38617. get: function () {
  38618. return this._useLogarithmicDepth;
  38619. },
  38620. set: function (value) {
  38621. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38622. },
  38623. enumerable: true,
  38624. configurable: true
  38625. });
  38626. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38627. if (this._linkRefractionWithTransparency) {
  38628. return false;
  38629. }
  38630. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38631. };
  38632. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38633. if (this._linkRefractionWithTransparency) {
  38634. return false;
  38635. }
  38636. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  38637. };
  38638. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38639. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  38640. };
  38641. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38642. return this._albedoTexture;
  38643. };
  38644. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  38645. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  38646. };
  38647. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  38648. if (!useScalarInLinear) {
  38649. color.toLinearSpaceToRef(ref);
  38650. }
  38651. else {
  38652. ref.r = color.r;
  38653. ref.g = color.g;
  38654. ref.b = color.b;
  38655. }
  38656. };
  38657. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  38658. var lightIndex = 0;
  38659. var depthValuesAlreadySet = false;
  38660. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38661. var light = _a[_i];
  38662. var useUbo = light._uniformBuffer.useUbo;
  38663. var scaledIntensity = light.getScaledIntensity();
  38664. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  38665. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  38666. // GAMMA CORRECTION.
  38667. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  38668. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  38669. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  38670. if (defines["SPECULARTERM"]) {
  38671. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  38672. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  38673. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  38674. }
  38675. // Shadows
  38676. if (scene.shadowsEnabled) {
  38677. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  38678. }
  38679. light._uniformBuffer.update();
  38680. lightIndex++;
  38681. if (lightIndex === maxSimultaneousLights)
  38682. break;
  38683. }
  38684. };
  38685. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38686. if (this.isFrozen) {
  38687. if (this._wasPreviouslyReady) {
  38688. return true;
  38689. }
  38690. }
  38691. if (!subMesh._materialDefines) {
  38692. subMesh._materialDefines = new PBRMaterialDefines();
  38693. }
  38694. var scene = this.getScene();
  38695. var defines = subMesh._materialDefines;
  38696. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38697. if (defines._renderId === scene.getRenderId()) {
  38698. return true;
  38699. }
  38700. }
  38701. var engine = scene.getEngine();
  38702. // Lights
  38703. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38704. defines._needNormals = true;
  38705. // Textures
  38706. if (defines._areTexturesDirty) {
  38707. defines._needUVs = false;
  38708. if (scene.texturesEnabled) {
  38709. if (scene.getEngine().getCaps().textureLOD) {
  38710. defines.LODBASEDMICROSFURACE = true;
  38711. }
  38712. defines.LDROUTPUT = this._ldrOutput;
  38713. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38714. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38715. return false;
  38716. }
  38717. defines._needUVs = true;
  38718. defines.ALBEDO = true;
  38719. }
  38720. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38721. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38722. return false;
  38723. }
  38724. defines._needUVs = true;
  38725. defines.AMBIENT = true;
  38726. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38727. }
  38728. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38729. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38730. return false;
  38731. }
  38732. defines._needUVs = true;
  38733. defines.OPACITY = true;
  38734. if (this._opacityTexture.getAlphaFromRGB) {
  38735. defines.OPACITYRGB = true;
  38736. }
  38737. }
  38738. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  38739. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38740. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38741. return false;
  38742. }
  38743. defines.REFLECTION = true;
  38744. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38745. defines.INVERTCUBICMAP = true;
  38746. }
  38747. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38748. switch (reflectionTexture.coordinatesMode) {
  38749. case BABYLON.Texture.CUBIC_MODE:
  38750. case BABYLON.Texture.INVCUBIC_MODE:
  38751. defines.REFLECTIONMAP_CUBIC = true;
  38752. break;
  38753. case BABYLON.Texture.EXPLICIT_MODE:
  38754. defines.REFLECTIONMAP_EXPLICIT = true;
  38755. break;
  38756. case BABYLON.Texture.PLANAR_MODE:
  38757. defines.REFLECTIONMAP_PLANAR = true;
  38758. break;
  38759. case BABYLON.Texture.PROJECTION_MODE:
  38760. defines.REFLECTIONMAP_PROJECTION = true;
  38761. break;
  38762. case BABYLON.Texture.SKYBOX_MODE:
  38763. defines.REFLECTIONMAP_SKYBOX = true;
  38764. break;
  38765. case BABYLON.Texture.SPHERICAL_MODE:
  38766. defines.REFLECTIONMAP_SPHERICAL = true;
  38767. break;
  38768. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38769. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38770. break;
  38771. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38772. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38773. break;
  38774. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38775. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38776. break;
  38777. }
  38778. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  38779. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38780. if (reflectionTexture.isPMREM) {
  38781. defines.USEPMREMREFLECTION = true;
  38782. }
  38783. }
  38784. }
  38785. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38786. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38787. return false;
  38788. }
  38789. defines._needUVs = true;
  38790. defines.LIGHTMAP = true;
  38791. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38792. }
  38793. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38794. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38795. return false;
  38796. }
  38797. defines._needUVs = true;
  38798. defines.EMISSIVE = true;
  38799. }
  38800. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38801. if (this._metallicTexture) {
  38802. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38803. return false;
  38804. }
  38805. defines._needUVs = true;
  38806. defines.METALLICWORKFLOW = true;
  38807. defines.METALLICMAP = true;
  38808. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38809. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38810. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38811. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38812. }
  38813. else if (this._reflectivityTexture) {
  38814. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38815. return false;
  38816. }
  38817. defines._needUVs = true;
  38818. defines.REFLECTIVITY = true;
  38819. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38820. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38821. }
  38822. if (this._microSurfaceTexture) {
  38823. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38824. return false;
  38825. }
  38826. defines._needUVs = true;
  38827. defines.MICROSURFACEMAP = true;
  38828. }
  38829. }
  38830. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38831. // Bump texure can not be none blocking.
  38832. if (!this._bumpTexture.isReady()) {
  38833. return false;
  38834. }
  38835. defines._needUVs = true;
  38836. defines.BUMP = true;
  38837. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38838. defines.PARALLAX = true;
  38839. if (this._useParallaxOcclusion) {
  38840. defines.PARALLAXOCCLUSION = true;
  38841. }
  38842. }
  38843. if (this._invertNormalMapX) {
  38844. defines.INVERTNORMALMAPX = true;
  38845. }
  38846. if (this._invertNormalMapY) {
  38847. defines.INVERTNORMALMAPY = true;
  38848. }
  38849. if (scene._mirroredCameraPosition) {
  38850. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  38851. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  38852. }
  38853. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  38854. }
  38855. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38856. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38857. return false;
  38858. }
  38859. defines._needUVs = true;
  38860. defines.REFRACTION = true;
  38861. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38862. if (this._linkRefractionWithTransparency) {
  38863. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38864. }
  38865. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  38866. defines.REFRACTIONMAPINLINEARSPACE = true;
  38867. if (this._refractionTexture.isPMREM) {
  38868. defines.USEPMREMREFRACTION = true;
  38869. }
  38870. }
  38871. }
  38872. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  38873. // Color Grading texure can not be none blocking.
  38874. if (!this._cameraColorGradingTexture.isReady()) {
  38875. return false;
  38876. }
  38877. defines.CAMERACOLORGRADING = true;
  38878. }
  38879. if (!this.backFaceCulling && this._twoSidedLighting) {
  38880. defines.TWOSIDEDLIGHTING = true;
  38881. }
  38882. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38883. defines.ALPHAFROMALBEDO = true;
  38884. }
  38885. if (this._useEmissiveAsIllumination) {
  38886. defines.EMISSIVEASILLUMINATION = true;
  38887. }
  38888. if (this._cameraContrast != 1) {
  38889. defines.CAMERACONTRAST = true;
  38890. }
  38891. if (this._cameraExposure != 1) {
  38892. defines.CAMERATONEMAP = true;
  38893. }
  38894. if (this._cameraColorCurves) {
  38895. defines.CAMERACOLORCURVES = true;
  38896. }
  38897. if (this._useSpecularOverAlpha) {
  38898. defines.SPECULAROVERALPHA = true;
  38899. }
  38900. if (this._usePhysicalLightFalloff) {
  38901. defines.USEPHYSICALLIGHTFALLOFF = true;
  38902. }
  38903. if (this._useRadianceOverAlpha) {
  38904. defines.RADIANCEOVERALPHA = true;
  38905. }
  38906. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38907. defines.METALLICWORKFLOW = true;
  38908. }
  38909. defines.ALPHATESTVALUE = this._alphaCutOff;
  38910. }
  38911. }
  38912. if (defines._areFresnelDirty) {
  38913. if (BABYLON.StandardMaterial.FresnelEnabled) {
  38914. // Fresnel
  38915. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  38916. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38917. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  38918. defines.OPACITYFRESNEL = true;
  38919. }
  38920. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38921. defines.EMISSIVEFRESNEL = true;
  38922. }
  38923. defines.FRESNEL = true;
  38924. }
  38925. }
  38926. }
  38927. // Misc.
  38928. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  38929. // Values that need to be evaluated on every frame
  38930. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  38931. // Attribs
  38932. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  38933. if (mesh) {
  38934. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38935. mesh.createNormals(true);
  38936. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  38937. }
  38938. }
  38939. }
  38940. // Get correct effect
  38941. if (defines.isDirty) {
  38942. defines.markAsProcessed();
  38943. scene.resetCachedMaterial();
  38944. // Fallbacks
  38945. var fallbacks = new BABYLON.EffectFallbacks();
  38946. if (defines.REFLECTION) {
  38947. fallbacks.addFallback(0, "REFLECTION");
  38948. }
  38949. if (defines.REFRACTION) {
  38950. fallbacks.addFallback(0, "REFRACTION");
  38951. }
  38952. if (defines.REFLECTIVITY) {
  38953. fallbacks.addFallback(0, "REFLECTIVITY");
  38954. }
  38955. if (defines.BUMP) {
  38956. fallbacks.addFallback(0, "BUMP");
  38957. }
  38958. if (defines.PARALLAX) {
  38959. fallbacks.addFallback(1, "PARALLAX");
  38960. }
  38961. if (defines.PARALLAXOCCLUSION) {
  38962. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38963. }
  38964. if (defines.SPECULAROVERALPHA) {
  38965. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38966. }
  38967. if (defines.FOG) {
  38968. fallbacks.addFallback(1, "FOG");
  38969. }
  38970. if (defines.POINTSIZE) {
  38971. fallbacks.addFallback(0, "POINTSIZE");
  38972. }
  38973. if (defines.LOGARITHMICDEPTH) {
  38974. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38975. }
  38976. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38977. if (defines.SPECULARTERM) {
  38978. fallbacks.addFallback(0, "SPECULARTERM");
  38979. }
  38980. if (defines.OPACITYFRESNEL) {
  38981. fallbacks.addFallback(1, "OPACITYFRESNEL");
  38982. }
  38983. if (defines.EMISSIVEFRESNEL) {
  38984. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  38985. }
  38986. if (defines.FRESNEL) {
  38987. fallbacks.addFallback(3, "FRESNEL");
  38988. }
  38989. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38990. fallbacks.addCPUSkinningFallback(0, mesh);
  38991. }
  38992. //Attributes
  38993. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38994. if (defines.NORMAL) {
  38995. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38996. }
  38997. if (defines.TANGENT) {
  38998. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38999. }
  39000. if (defines.UV1) {
  39001. attribs.push(BABYLON.VertexBuffer.UVKind);
  39002. }
  39003. if (defines.UV2) {
  39004. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39005. }
  39006. if (defines.VERTEXCOLOR) {
  39007. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39008. }
  39009. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39010. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39011. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39012. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39013. "vFogInfos", "vFogColor", "pointSize",
  39014. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39015. "mBones",
  39016. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39017. "depthValues",
  39018. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  39019. "vLightingIntensity",
  39020. "logarithmicDepthConstant",
  39021. "vSphericalX", "vSphericalY", "vSphericalZ",
  39022. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39023. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39024. "vMicrosurfaceTextureLods",
  39025. "vCameraInfos"
  39026. ];
  39027. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39028. var uniformBuffers = ["Material", "Scene"];
  39029. if (defines.CAMERACOLORCURVES) {
  39030. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  39031. }
  39032. if (defines.CAMERACOLORGRADING) {
  39033. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  39034. }
  39035. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39036. uniformsNames: uniforms,
  39037. uniformBuffersNames: uniformBuffers,
  39038. samplers: samplers,
  39039. defines: defines,
  39040. maxSimultaneousLights: this._maxSimultaneousLights
  39041. });
  39042. var onCompiled = function (effect) {
  39043. if (this.onCompiled) {
  39044. this.onCompiled(effect);
  39045. }
  39046. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39047. }.bind(this);
  39048. var join = defines.toString();
  39049. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  39050. attributes: attribs,
  39051. uniformsNames: uniforms,
  39052. uniformBuffersNames: uniformBuffers,
  39053. samplers: samplers,
  39054. defines: join,
  39055. fallbacks: fallbacks,
  39056. onCompiled: onCompiled,
  39057. onError: this.onError,
  39058. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39059. }, engine), defines);
  39060. this.buildUniformLayout();
  39061. }
  39062. if (!subMesh.effect.isReady()) {
  39063. return false;
  39064. }
  39065. defines._renderId = scene.getRenderId();
  39066. this._wasPreviouslyReady = true;
  39067. return true;
  39068. };
  39069. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39070. // Order is important !
  39071. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39072. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39073. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39074. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39075. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39076. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39077. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39078. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39079. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39080. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39081. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39082. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39083. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39084. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39085. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39086. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39087. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39088. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39089. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39090. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39091. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39092. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39093. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39094. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  39095. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39096. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39097. this._uniformBuffer.addUniform("opacityParts", 4);
  39098. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39099. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39100. this._uniformBuffer.addUniform("pointSize", 1);
  39101. this._uniformBuffer.create();
  39102. };
  39103. PBRBaseMaterial.prototype.unbind = function () {
  39104. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39105. this._uniformBuffer.setTexture("reflection2DSampler", null);
  39106. }
  39107. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39108. this._uniformBuffer.setTexture("refraction2DSampler", null);
  39109. }
  39110. _super.prototype.unbind.call(this);
  39111. };
  39112. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39113. this._activeEffect.setMatrix("world", world);
  39114. };
  39115. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39116. var scene = this.getScene();
  39117. var defines = subMesh._materialDefines;
  39118. if (!defines) {
  39119. return;
  39120. }
  39121. var effect = subMesh.effect;
  39122. this._activeEffect = effect;
  39123. // Matrices
  39124. this.bindOnlyWorldMatrix(world);
  39125. // Bones
  39126. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  39127. if (this._mustRebind(scene, effect, mesh.visibility)) {
  39128. this._uniformBuffer.bindToEffect(effect, "Material");
  39129. this.bindViewProjection(effect);
  39130. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39131. // Fresnel
  39132. if (BABYLON.StandardMaterial.FresnelEnabled) {
  39133. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  39134. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  39135. }
  39136. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  39137. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  39138. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  39139. }
  39140. }
  39141. // Texture uniforms
  39142. if (scene.texturesEnabled) {
  39143. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39144. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39145. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  39146. }
  39147. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39148. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39149. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  39150. }
  39151. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39152. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39153. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  39154. }
  39155. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  39156. ;
  39157. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39158. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  39159. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39160. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39161. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  39162. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  39163. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  39164. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  39165. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  39166. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  39167. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  39168. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  39169. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  39170. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  39171. }
  39172. }
  39173. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39174. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39175. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  39176. }
  39177. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39178. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39179. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  39180. }
  39181. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39182. if (this._metallicTexture) {
  39183. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39184. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  39185. }
  39186. else if (this._reflectivityTexture) {
  39187. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39188. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  39189. }
  39190. if (this._microSurfaceTexture) {
  39191. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39192. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  39193. }
  39194. }
  39195. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39196. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39197. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  39198. }
  39199. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39200. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  39201. var depth = 1.0;
  39202. if (!this._refractionTexture.isCube) {
  39203. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39204. if (this._refractionTexture.depth) {
  39205. depth = this._refractionTexture.depth;
  39206. }
  39207. }
  39208. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39209. }
  39210. if ((reflectionTexture || this._refractionTexture)) {
  39211. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  39212. }
  39213. }
  39214. // Point size
  39215. if (this.pointsCloud) {
  39216. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39217. }
  39218. // Colors
  39219. if (defines.METALLICWORKFLOW) {
  39220. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39221. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39222. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39223. }
  39224. else {
  39225. // GAMMA CORRECTION.
  39226. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  39227. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  39228. }
  39229. // GAMMA CORRECTION.
  39230. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  39231. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  39232. // GAMMA CORRECTION.
  39233. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  39234. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  39235. // GAMMA CORRECTION.
  39236. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  39237. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  39238. // Misc
  39239. this._lightingInfos.x = this._directIntensity;
  39240. this._lightingInfos.y = this._emissiveIntensity;
  39241. this._lightingInfos.z = this._environmentIntensity;
  39242. this._lightingInfos.w = this._specularIntensity;
  39243. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39244. }
  39245. // Textures
  39246. if (scene.texturesEnabled) {
  39247. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39248. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39249. }
  39250. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39251. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39252. }
  39253. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39254. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39255. }
  39256. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39257. if (reflectionTexture.isCube) {
  39258. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  39259. }
  39260. else {
  39261. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  39262. }
  39263. }
  39264. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39265. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39266. }
  39267. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39268. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39269. }
  39270. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39271. if (this._metallicTexture) {
  39272. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39273. }
  39274. else if (this._reflectivityTexture) {
  39275. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39276. }
  39277. if (this._microSurfaceTexture) {
  39278. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39279. }
  39280. }
  39281. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39282. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39283. }
  39284. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39285. if (this._refractionTexture.isCube) {
  39286. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  39287. }
  39288. else {
  39289. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  39290. }
  39291. }
  39292. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  39293. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._activeEffect);
  39294. }
  39295. }
  39296. // Clip plane
  39297. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  39298. // Colors
  39299. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39300. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  39301. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39302. }
  39303. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  39304. // Lights
  39305. if (scene.lightsEnabled && !this._disableLighting) {
  39306. BABYLON.PBRMaterial.BindLights(scene, mesh, this._activeEffect, defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39307. }
  39308. // View
  39309. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39310. this.bindView(effect);
  39311. }
  39312. // Fog
  39313. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  39314. // Morph targets
  39315. if (defines.NUM_MORPH_INFLUENCERS) {
  39316. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  39317. }
  39318. this._cameraInfos.x = this._cameraExposure;
  39319. this._cameraInfos.y = this._cameraContrast;
  39320. effect.setVector4("vCameraInfos", this._cameraInfos);
  39321. if (this._cameraColorCurves) {
  39322. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._activeEffect);
  39323. }
  39324. // Log. depth
  39325. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  39326. }
  39327. this._uniformBuffer.update();
  39328. this._afterBind(mesh);
  39329. scene = null;
  39330. };
  39331. PBRBaseMaterial.prototype.getAnimatables = function () {
  39332. var results = [];
  39333. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39334. results.push(this._albedoTexture);
  39335. }
  39336. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39337. results.push(this._ambientTexture);
  39338. }
  39339. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39340. results.push(this._opacityTexture);
  39341. }
  39342. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39343. results.push(this._reflectionTexture);
  39344. }
  39345. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39346. results.push(this._emissiveTexture);
  39347. }
  39348. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39349. results.push(this._metallicTexture);
  39350. }
  39351. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39352. results.push(this._reflectivityTexture);
  39353. }
  39354. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39355. results.push(this._bumpTexture);
  39356. }
  39357. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39358. results.push(this._lightmapTexture);
  39359. }
  39360. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39361. results.push(this._refractionTexture);
  39362. }
  39363. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  39364. results.push(this._cameraColorGradingTexture);
  39365. }
  39366. return results;
  39367. };
  39368. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39369. if (forceDisposeTextures) {
  39370. if (this._albedoTexture) {
  39371. this._albedoTexture.dispose();
  39372. }
  39373. if (this._ambientTexture) {
  39374. this._ambientTexture.dispose();
  39375. }
  39376. if (this._opacityTexture) {
  39377. this._opacityTexture.dispose();
  39378. }
  39379. if (this._reflectionTexture) {
  39380. this._reflectionTexture.dispose();
  39381. }
  39382. if (this._emissiveTexture) {
  39383. this._emissiveTexture.dispose();
  39384. }
  39385. if (this._metallicTexture) {
  39386. this._metallicTexture.dispose();
  39387. }
  39388. if (this._reflectivityTexture) {
  39389. this._reflectivityTexture.dispose();
  39390. }
  39391. if (this._bumpTexture) {
  39392. this._bumpTexture.dispose();
  39393. }
  39394. if (this._lightmapTexture) {
  39395. this._lightmapTexture.dispose();
  39396. }
  39397. if (this._refractionTexture) {
  39398. this._refractionTexture.dispose();
  39399. }
  39400. if (this._cameraColorGradingTexture) {
  39401. this._cameraColorGradingTexture.dispose();
  39402. }
  39403. }
  39404. this._renderTargets.dispose();
  39405. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39406. };
  39407. return PBRBaseMaterial;
  39408. }(BABYLON.PushMaterial));
  39409. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  39410. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39411. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  39412. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  39413. __decorate([
  39414. BABYLON.serialize()
  39415. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39416. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39417. })(BABYLON || (BABYLON = {}));
  39418. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39419. var BABYLON;
  39420. (function (BABYLON) {
  39421. var Internals;
  39422. (function (Internals) {
  39423. /**
  39424. * The Physically based simple base material of BJS.
  39425. *
  39426. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39427. * It is used as the base class for both the specGloss and metalRough conventions.
  39428. */
  39429. var PBRBaseSimpleMaterial = (function (_super) {
  39430. __extends(PBRBaseSimpleMaterial, _super);
  39431. /**
  39432. * Instantiates a new PBRMaterial instance.
  39433. *
  39434. * @param name The material name
  39435. * @param scene The scene the material will be use in.
  39436. */
  39437. function PBRBaseSimpleMaterial(name, scene) {
  39438. var _this = _super.call(this, name, scene) || this;
  39439. /**
  39440. * Number of Simultaneous lights allowed on the material.
  39441. */
  39442. _this.maxSimultaneousLights = 4;
  39443. /**
  39444. * If sets to true, disables all the lights affecting the material.
  39445. */
  39446. _this.disableLighting = false;
  39447. /**
  39448. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39449. */
  39450. _this.invertNormalMapX = false;
  39451. /**
  39452. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39453. */
  39454. _this.invertNormalMapY = false;
  39455. /**
  39456. * Emissivie color used to self-illuminate the model.
  39457. */
  39458. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39459. /**
  39460. * Occlusion Channel Strenght.
  39461. */
  39462. _this.occlusionStrength = 1.0;
  39463. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39464. _this._useEmissiveAsIllumination = true;
  39465. _this._useAmbientInGrayScale = true;
  39466. _this._useScalarInLinearSpace = true;
  39467. return _this;
  39468. }
  39469. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  39470. /**
  39471. * Gets the current transparency mode.
  39472. */
  39473. get: function () {
  39474. return this._transparencyMode;
  39475. },
  39476. /**
  39477. * Sets the transparency mode of the material.
  39478. */
  39479. set: function (value) {
  39480. if (this._transparencyMode === value) {
  39481. return;
  39482. }
  39483. this._transparencyMode = value;
  39484. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  39485. this._forceAlphaTest = true;
  39486. }
  39487. else {
  39488. this._forceAlphaTest = false;
  39489. }
  39490. this._markAllSubMeshesAsTexturesDirty();
  39491. },
  39492. enumerable: true,
  39493. configurable: true
  39494. });
  39495. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39496. /**
  39497. * Gets the current double sided mode.
  39498. */
  39499. get: function () {
  39500. return this._twoSidedLighting;
  39501. },
  39502. /**
  39503. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39504. */
  39505. set: function (value) {
  39506. if (this._twoSidedLighting === value) {
  39507. return;
  39508. }
  39509. this._twoSidedLighting = value;
  39510. this.backFaceCulling = !value;
  39511. this._markAllSubMeshesAsTexturesDirty();
  39512. },
  39513. enumerable: true,
  39514. configurable: true
  39515. });
  39516. /**
  39517. * Specifies wether or not the alpha value of the albedo texture should be used.
  39518. */
  39519. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39520. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39521. };
  39522. /**
  39523. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  39524. */
  39525. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  39526. if (this._linkRefractionWithTransparency) {
  39527. return false;
  39528. }
  39529. return (this.alpha < 1.0) ||
  39530. (this._shouldUseAlphaFromAlbedoTexture() &&
  39531. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  39532. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  39533. };
  39534. /**
  39535. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  39536. */
  39537. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  39538. if (this._linkRefractionWithTransparency) {
  39539. return false;
  39540. }
  39541. return this._shouldUseAlphaFromAlbedoTexture() &&
  39542. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  39543. };
  39544. return PBRBaseSimpleMaterial;
  39545. }(BABYLON.PBRBaseMaterial));
  39546. __decorate([
  39547. BABYLON.serialize(),
  39548. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39549. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39550. __decorate([
  39551. BABYLON.serialize(),
  39552. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39553. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39554. __decorate([
  39555. BABYLON.serializeAsTexture(),
  39556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39557. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39558. __decorate([
  39559. BABYLON.serialize(),
  39560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39561. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39562. __decorate([
  39563. BABYLON.serialize(),
  39564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39565. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39566. __decorate([
  39567. BABYLON.serializeAsTexture(),
  39568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39569. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39570. __decorate([
  39571. BABYLON.serializeAsColor3("emissive"),
  39572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39573. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39574. __decorate([
  39575. BABYLON.serializeAsTexture(),
  39576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39577. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39578. __decorate([
  39579. BABYLON.serialize(),
  39580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39581. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39582. __decorate([
  39583. BABYLON.serializeAsTexture(),
  39584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39585. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39586. __decorate([
  39587. BABYLON.serialize(),
  39588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39589. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39590. __decorate([
  39591. BABYLON.serialize()
  39592. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  39593. __decorate([
  39594. BABYLON.serialize()
  39595. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39596. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39597. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39598. })(BABYLON || (BABYLON = {}));
  39599. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39600. var BABYLON;
  39601. (function (BABYLON) {
  39602. /**
  39603. * The Physically based material of BJS.
  39604. *
  39605. * This offers the main features of a standard PBR material.
  39606. * For more information, please refer to the documentation :
  39607. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39608. */
  39609. var PBRMaterial = (function (_super) {
  39610. __extends(PBRMaterial, _super);
  39611. /**
  39612. * Instantiates a new PBRMaterial instance.
  39613. *
  39614. * @param name The material name
  39615. * @param scene The scene the material will be use in.
  39616. */
  39617. function PBRMaterial(name, scene) {
  39618. var _this = _super.call(this, name, scene) || this;
  39619. /**
  39620. * Intensity of the direct lights e.g. the four lights available in your scene.
  39621. * This impacts both the direct diffuse and specular highlights.
  39622. */
  39623. _this.directIntensity = 1.0;
  39624. /**
  39625. * Intensity of the emissive part of the material.
  39626. * This helps controlling the emissive effect without modifying the emissive color.
  39627. */
  39628. _this.emissiveIntensity = 1.0;
  39629. /**
  39630. * Intensity of the environment e.g. how much the environment will light the object
  39631. * either through harmonics for rough material or through the refelction for shiny ones.
  39632. */
  39633. _this.environmentIntensity = 1.0;
  39634. /**
  39635. * This is a special control allowing the reduction of the specular highlights coming from the
  39636. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39637. */
  39638. _this.specularIntensity = 1.0;
  39639. /**
  39640. * Debug Control allowing disabling the bump map on this material.
  39641. */
  39642. _this.disableBumpMap = false;
  39643. /**
  39644. * The camera exposure used on this material.
  39645. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39646. * This corresponds to a photographic exposure.
  39647. */
  39648. _this.cameraExposure = 1.0;
  39649. /**
  39650. * The camera contrast used on this material.
  39651. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  39652. */
  39653. _this.cameraContrast = 1.0;
  39654. /**
  39655. * Color Grading 2D Lookup Texture.
  39656. * This allows special effects like sepia, black and white to sixties rendering style.
  39657. */
  39658. _this.cameraColorGradingTexture = null;
  39659. /**
  39660. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39661. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39662. * 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;
  39663. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39664. */
  39665. _this.cameraColorCurves = null;
  39666. /**
  39667. * AKA Occlusion Texture Intensity in other nomenclature.
  39668. */
  39669. _this.ambientTextureStrength = 1.0;
  39670. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39671. /**
  39672. * AKA Diffuse Color in other nomenclature.
  39673. */
  39674. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39675. /**
  39676. * AKA Specular Color in other nomenclature.
  39677. */
  39678. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39679. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39680. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39681. /**
  39682. * AKA Glossiness in other nomenclature.
  39683. */
  39684. _this.microSurface = 0.9;
  39685. /**
  39686. * source material index of refraction (IOR)' / 'destination material IOR.
  39687. */
  39688. _this.indexOfRefraction = 0.66;
  39689. /**
  39690. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39691. */
  39692. _this.invertRefractionY = false;
  39693. /**
  39694. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39695. * Materials half opaque for instance using refraction could benefit from this control.
  39696. */
  39697. _this.linkRefractionWithTransparency = false;
  39698. _this.useLightmapAsShadowmap = false;
  39699. /**
  39700. * In this mode, the emissive informtaion will always be added to the lighting once.
  39701. * A light for instance can be thought as emissive.
  39702. */
  39703. _this.useEmissiveAsIllumination = false;
  39704. /**
  39705. * Secifies that the alpha is coming form the albedo channel alpha channel.
  39706. */
  39707. _this.useAlphaFromAlbedoTexture = false;
  39708. /**
  39709. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39710. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39711. */
  39712. _this.useSpecularOverAlpha = true;
  39713. /**
  39714. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39715. */
  39716. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39717. /**
  39718. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39719. */
  39720. _this.useRoughnessFromMetallicTextureAlpha = true;
  39721. /**
  39722. * Specifies if the metallic texture contains the roughness information in its green channel.
  39723. */
  39724. _this.useRoughnessFromMetallicTextureGreen = false;
  39725. /**
  39726. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39727. */
  39728. _this.useMetallnessFromMetallicTextureBlue = false;
  39729. /**
  39730. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39731. */
  39732. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39733. /**
  39734. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39735. */
  39736. _this.useAmbientInGrayScale = false;
  39737. /**
  39738. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39739. * The material will try to infer what glossiness each pixel should be.
  39740. */
  39741. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39742. /**
  39743. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  39744. * the creation of the material.
  39745. */
  39746. _this.useScalarInLinearSpace = false;
  39747. /**
  39748. * BJS is using an harcoded light falloff based on a manually sets up range.
  39749. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39750. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39751. */
  39752. _this.usePhysicalLightFalloff = true;
  39753. /**
  39754. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39755. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39756. */
  39757. _this.useRadianceOverAlpha = true;
  39758. /**
  39759. * Allows using the bump map in parallax mode.
  39760. */
  39761. _this.useParallax = false;
  39762. /**
  39763. * Allows using the bump map in parallax occlusion mode.
  39764. */
  39765. _this.useParallaxOcclusion = false;
  39766. /**
  39767. * Controls the scale bias of the parallax mode.
  39768. */
  39769. _this.parallaxScaleBias = 0.05;
  39770. /**
  39771. * If sets to true, disables all the lights affecting the material.
  39772. */
  39773. _this.disableLighting = false;
  39774. /**
  39775. * Number of Simultaneous lights allowed on the material.
  39776. */
  39777. _this.maxSimultaneousLights = 4;
  39778. /**
  39779. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39780. */
  39781. _this.invertNormalMapX = false;
  39782. /**
  39783. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39784. */
  39785. _this.invertNormalMapY = false;
  39786. /**
  39787. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39788. */
  39789. _this.twoSidedLighting = false;
  39790. return _this;
  39791. }
  39792. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39793. /**
  39794. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39795. */
  39796. get: function () {
  39797. return this._PBRMATERIAL_OPAQUE;
  39798. },
  39799. enumerable: true,
  39800. configurable: true
  39801. });
  39802. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39803. /**
  39804. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39805. */
  39806. get: function () {
  39807. return this._PBRMATERIAL_ALPHATEST;
  39808. },
  39809. enumerable: true,
  39810. configurable: true
  39811. });
  39812. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39813. /**
  39814. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39815. */
  39816. get: function () {
  39817. return this._PBRMATERIAL_ALPHABLEND;
  39818. },
  39819. enumerable: true,
  39820. configurable: true
  39821. });
  39822. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39823. /**
  39824. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39825. * They are also discarded below the alpha cutoff threshold to improve performances.
  39826. */
  39827. get: function () {
  39828. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39829. },
  39830. enumerable: true,
  39831. configurable: true
  39832. });
  39833. PBRMaterial.prototype.getClassName = function () {
  39834. return "PBRMaterial";
  39835. };
  39836. PBRMaterial.prototype.clone = function (name) {
  39837. var _this = this;
  39838. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39839. };
  39840. PBRMaterial.prototype.serialize = function () {
  39841. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39842. serializationObject.customType = "BABYLON.PBRMaterial";
  39843. return serializationObject;
  39844. };
  39845. // Statics
  39846. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39847. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39848. };
  39849. return PBRMaterial;
  39850. }(BABYLON.PBRBaseMaterial));
  39851. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39852. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39853. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39854. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39855. __decorate([
  39856. BABYLON.serialize(),
  39857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39858. ], PBRMaterial.prototype, "directIntensity", void 0);
  39859. __decorate([
  39860. BABYLON.serialize(),
  39861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39862. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39863. __decorate([
  39864. BABYLON.serialize(),
  39865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39866. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39867. __decorate([
  39868. BABYLON.serialize(),
  39869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39870. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39871. __decorate([
  39872. BABYLON.serialize(),
  39873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39874. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39875. __decorate([
  39876. BABYLON.serialize(),
  39877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39878. ], PBRMaterial.prototype, "cameraExposure", void 0);
  39879. __decorate([
  39880. BABYLON.serialize(),
  39881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39882. ], PBRMaterial.prototype, "cameraContrast", void 0);
  39883. __decorate([
  39884. BABYLON.serializeAsTexture(),
  39885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39886. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  39887. __decorate([
  39888. BABYLON.serializeAsColorCurves(),
  39889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39890. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  39891. __decorate([
  39892. BABYLON.serializeAsTexture(),
  39893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39894. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39895. __decorate([
  39896. BABYLON.serializeAsTexture(),
  39897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39898. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39899. __decorate([
  39900. BABYLON.serialize(),
  39901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39902. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39903. __decorate([
  39904. BABYLON.serializeAsTexture(),
  39905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39906. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39907. __decorate([
  39908. BABYLON.serializeAsTexture(),
  39909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39910. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39911. __decorate([
  39912. BABYLON.serializeAsTexture(),
  39913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39914. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39915. __decorate([
  39916. BABYLON.serializeAsTexture(),
  39917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39918. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39919. __decorate([
  39920. BABYLON.serializeAsTexture(),
  39921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39922. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39923. __decorate([
  39924. BABYLON.serialize(),
  39925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39926. ], PBRMaterial.prototype, "metallic", void 0);
  39927. __decorate([
  39928. BABYLON.serialize(),
  39929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39930. ], PBRMaterial.prototype, "roughness", void 0);
  39931. __decorate([
  39932. BABYLON.serializeAsTexture(),
  39933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39934. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39935. __decorate([
  39936. BABYLON.serializeAsTexture(),
  39937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39938. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39939. __decorate([
  39940. BABYLON.serializeAsTexture(),
  39941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39942. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39943. __decorate([
  39944. BABYLON.serializeAsTexture(),
  39945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39946. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39947. __decorate([
  39948. BABYLON.serializeAsColor3("ambient"),
  39949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39950. ], PBRMaterial.prototype, "ambientColor", void 0);
  39951. __decorate([
  39952. BABYLON.serializeAsColor3("albedo"),
  39953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39954. ], PBRMaterial.prototype, "albedoColor", void 0);
  39955. __decorate([
  39956. BABYLON.serializeAsColor3("reflectivity"),
  39957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39958. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39959. __decorate([
  39960. BABYLON.serializeAsColor3("reflection"),
  39961. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39962. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39963. __decorate([
  39964. BABYLON.serializeAsColor3("emissive"),
  39965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39966. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39967. __decorate([
  39968. BABYLON.serialize(),
  39969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39970. ], PBRMaterial.prototype, "microSurface", void 0);
  39971. __decorate([
  39972. BABYLON.serialize(),
  39973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39974. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39975. __decorate([
  39976. BABYLON.serialize(),
  39977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39978. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39979. __decorate([
  39980. BABYLON.serializeAsFresnelParameters(),
  39981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39982. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  39983. __decorate([
  39984. BABYLON.serializeAsFresnelParameters(),
  39985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39986. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  39987. __decorate([
  39988. BABYLON.serialize(),
  39989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39990. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39991. __decorate([
  39992. BABYLON.serialize(),
  39993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39994. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39995. __decorate([
  39996. BABYLON.serialize(),
  39997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39998. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39999. __decorate([
  40000. BABYLON.serialize(),
  40001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40002. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  40003. __decorate([
  40004. BABYLON.serialize(),
  40005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40006. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40007. __decorate([
  40008. BABYLON.serialize(),
  40009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40010. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40011. __decorate([
  40012. BABYLON.serialize(),
  40013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40014. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40015. __decorate([
  40016. BABYLON.serialize(),
  40017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40018. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40019. __decorate([
  40020. BABYLON.serialize(),
  40021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40022. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40023. __decorate([
  40024. BABYLON.serialize(),
  40025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40026. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40027. __decorate([
  40028. BABYLON.serialize(),
  40029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40030. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40031. __decorate([
  40032. BABYLON.serialize(),
  40033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40034. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40035. __decorate([
  40036. BABYLON.serialize(),
  40037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40038. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  40039. __decorate([
  40040. BABYLON.serialize(),
  40041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40042. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40043. __decorate([
  40044. BABYLON.serialize(),
  40045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40046. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40047. __decorate([
  40048. BABYLON.serialize(),
  40049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40050. ], PBRMaterial.prototype, "useParallax", void 0);
  40051. __decorate([
  40052. BABYLON.serialize(),
  40053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40054. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40055. __decorate([
  40056. BABYLON.serialize(),
  40057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40058. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40059. __decorate([
  40060. BABYLON.serialize(),
  40061. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40062. ], PBRMaterial.prototype, "disableLighting", void 0);
  40063. __decorate([
  40064. BABYLON.serialize(),
  40065. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40066. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40067. __decorate([
  40068. BABYLON.serialize(),
  40069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40070. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40071. __decorate([
  40072. BABYLON.serialize(),
  40073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40074. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40075. __decorate([
  40076. BABYLON.serialize(),
  40077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40078. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40079. BABYLON.PBRMaterial = PBRMaterial;
  40080. })(BABYLON || (BABYLON = {}));
  40081. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40082. var BABYLON;
  40083. (function (BABYLON) {
  40084. /**
  40085. * The PBR material of BJS following the metal roughness convention.
  40086. *
  40087. * This fits to the define PBR convention in the GLTF definition:
  40088. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40089. */
  40090. var PBRMetallicRoughnessMaterial = (function (_super) {
  40091. __extends(PBRMetallicRoughnessMaterial, _super);
  40092. /**
  40093. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40094. *
  40095. * @param name The material name
  40096. * @param scene The scene the material will be use in.
  40097. */
  40098. function PBRMetallicRoughnessMaterial(name, scene) {
  40099. var _this = _super.call(this, name, scene) || this;
  40100. _this._useRoughnessFromMetallicTextureGreen = true;
  40101. _this._useMetallnessFromMetallicTextureBlue = true;
  40102. return _this;
  40103. }
  40104. /**
  40105. * Return the currrent class name of the material.
  40106. */
  40107. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40108. return "PBRMetallicRoughnessMaterial";
  40109. };
  40110. /**
  40111. * Serialize the material to a parsable JSON object.
  40112. */
  40113. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40114. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40115. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40116. return serializationObject;
  40117. };
  40118. /**
  40119. * Parses a JSON object correponding to the serialize function.
  40120. */
  40121. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40122. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40123. };
  40124. return PBRMetallicRoughnessMaterial;
  40125. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  40126. __decorate([
  40127. BABYLON.serializeAsTexture(),
  40128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40129. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40130. __decorate([
  40131. BABYLON.serializeAsTexture(),
  40132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40133. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40134. __decorate([
  40135. BABYLON.serialize(),
  40136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40137. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40138. __decorate([
  40139. BABYLON.serialize(),
  40140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40141. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40142. __decorate([
  40143. BABYLON.serializeAsTexture(),
  40144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  40145. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40146. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40147. })(BABYLON || (BABYLON = {}));
  40148. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40149. var BABYLON;
  40150. (function (BABYLON) {
  40151. /**
  40152. * The PBR material of BJS following the specular glossiness convention.
  40153. *
  40154. * This fits to the define PBR convention in the GLTF definition:
  40155. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40156. */
  40157. var PBRSpecularGlossinessMaterial = (function (_super) {
  40158. __extends(PBRSpecularGlossinessMaterial, _super);
  40159. /**
  40160. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40161. *
  40162. * @param name The material name
  40163. * @param scene The scene the material will be use in.
  40164. */
  40165. function PBRSpecularGlossinessMaterial(name, scene) {
  40166. var _this = _super.call(this, name, scene) || this;
  40167. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40168. return _this;
  40169. }
  40170. /**
  40171. * Return the currrent class name of the material.
  40172. */
  40173. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40174. return "PBRSpecularGlossinessMaterial";
  40175. };
  40176. /**
  40177. * Serialize the material to a parsable JSON object.
  40178. */
  40179. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40180. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40181. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40182. return serializationObject;
  40183. };
  40184. /**
  40185. * Parses a JSON object correponding to the serialize function.
  40186. */
  40187. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40188. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40189. };
  40190. return PBRSpecularGlossinessMaterial;
  40191. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  40192. __decorate([
  40193. BABYLON.serializeAsColor3(),
  40194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  40195. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40196. __decorate([
  40197. BABYLON.serializeAsTexture(),
  40198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  40199. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40200. __decorate([
  40201. BABYLON.serializeAsColor3(),
  40202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  40203. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40204. __decorate([
  40205. BABYLON.serialize(),
  40206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  40207. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40208. __decorate([
  40209. BABYLON.serializeAsTexture(),
  40210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  40211. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40212. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40213. })(BABYLON || (BABYLON = {}));
  40214. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40215. var BABYLON;
  40216. (function (BABYLON) {
  40217. var ShadowLight = (function (_super) {
  40218. __extends(ShadowLight, _super);
  40219. function ShadowLight() {
  40220. var _this = _super !== null && _super.apply(this, arguments) || this;
  40221. _this._needProjectionMatrixCompute = true;
  40222. return _this;
  40223. }
  40224. Object.defineProperty(ShadowLight.prototype, "direction", {
  40225. get: function () {
  40226. return this._direction;
  40227. },
  40228. set: function (value) {
  40229. this._direction = value;
  40230. },
  40231. enumerable: true,
  40232. configurable: true
  40233. });
  40234. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40235. get: function () {
  40236. return this._shadowMinZ;
  40237. },
  40238. set: function (value) {
  40239. this._shadowMinZ = value;
  40240. this.forceProjectionMatrixCompute();
  40241. },
  40242. enumerable: true,
  40243. configurable: true
  40244. });
  40245. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40246. get: function () {
  40247. return this._shadowMaxZ;
  40248. },
  40249. set: function (value) {
  40250. this._shadowMaxZ = value;
  40251. this.forceProjectionMatrixCompute();
  40252. },
  40253. enumerable: true,
  40254. configurable: true
  40255. });
  40256. /**
  40257. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40258. */
  40259. ShadowLight.prototype.computeTransformedInformation = function () {
  40260. if (this.parent && this.parent.getWorldMatrix) {
  40261. if (!this.transformedPosition) {
  40262. this.transformedPosition = BABYLON.Vector3.Zero();
  40263. }
  40264. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40265. // In case the direction is present.
  40266. if (this.direction) {
  40267. if (!this.transformedDirection) {
  40268. this.transformedDirection = BABYLON.Vector3.Zero();
  40269. }
  40270. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40271. }
  40272. return true;
  40273. }
  40274. return false;
  40275. };
  40276. /**
  40277. * Return the depth scale used for the shadow map.
  40278. */
  40279. ShadowLight.prototype.getDepthScale = function () {
  40280. return 30.0;
  40281. };
  40282. /**
  40283. * Returns the light direction (Vector3) for any passed face index.
  40284. */
  40285. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40286. return this.transformedDirection ? this.transformedDirection : this.direction;
  40287. };
  40288. /**
  40289. * Returns the DirectionalLight absolute position in the World.
  40290. */
  40291. ShadowLight.prototype.getAbsolutePosition = function () {
  40292. return this.transformedPosition ? this.transformedPosition : this.position;
  40293. };
  40294. /**
  40295. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40296. * Returns the updated DirectionalLight direction (Vector3).
  40297. */
  40298. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40299. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40300. return this.direction;
  40301. };
  40302. /**
  40303. * Returns the light rotation (Vector3).
  40304. */
  40305. ShadowLight.prototype.getRotation = function () {
  40306. this.direction.normalize();
  40307. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40308. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40309. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40310. };
  40311. /**
  40312. * Boolean : false by default.
  40313. */
  40314. ShadowLight.prototype.needCube = function () {
  40315. return false;
  40316. };
  40317. /**
  40318. * Specifies wether or not the projection matrix should be recomputed this frame.
  40319. */
  40320. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40321. return this._needProjectionMatrixCompute;
  40322. };
  40323. /**
  40324. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40325. */
  40326. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40327. this._needProjectionMatrixCompute = true;
  40328. };
  40329. /**
  40330. * Get the world matrix of the sahdow lights.
  40331. */
  40332. ShadowLight.prototype._getWorldMatrix = function () {
  40333. if (!this._worldMatrix) {
  40334. this._worldMatrix = BABYLON.Matrix.Identity();
  40335. }
  40336. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40337. return this._worldMatrix;
  40338. };
  40339. /**
  40340. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40341. * Returns the light.
  40342. */
  40343. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40344. if (this.customProjectionMatrixBuilder) {
  40345. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40346. }
  40347. else {
  40348. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40349. }
  40350. return this;
  40351. };
  40352. return ShadowLight;
  40353. }(BABYLON.Light));
  40354. __decorate([
  40355. BABYLON.serializeAsVector3()
  40356. ], ShadowLight.prototype, "position", void 0);
  40357. __decorate([
  40358. BABYLON.serializeAsVector3()
  40359. ], ShadowLight.prototype, "direction", null);
  40360. __decorate([
  40361. BABYLON.serialize()
  40362. ], ShadowLight.prototype, "shadowMinZ", null);
  40363. __decorate([
  40364. BABYLON.serialize()
  40365. ], ShadowLight.prototype, "shadowMaxZ", null);
  40366. BABYLON.ShadowLight = ShadowLight;
  40367. })(BABYLON || (BABYLON = {}));
  40368. //# sourceMappingURL=babylon.shadowLight.js.map
  40369. var BABYLON;
  40370. (function (BABYLON) {
  40371. var PointLight = (function (_super) {
  40372. __extends(PointLight, _super);
  40373. /**
  40374. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40375. * A PointLight emits the light in every direction.
  40376. * It can cast shadows.
  40377. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40378. * ```javascript
  40379. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40380. * ```
  40381. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40382. */
  40383. function PointLight(name, position, scene) {
  40384. var _this = _super.call(this, name, scene) || this;
  40385. _this._shadowAngle = Math.PI / 2;
  40386. _this.position = position;
  40387. return _this;
  40388. }
  40389. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40390. /**
  40391. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40392. * This specifies what angle the shadow will use to be created.
  40393. *
  40394. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40395. */
  40396. get: function () {
  40397. return this._shadowAngle;
  40398. },
  40399. /**
  40400. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40401. * This specifies what angle the shadow will use to be created.
  40402. *
  40403. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40404. */
  40405. set: function (value) {
  40406. this._shadowAngle = value;
  40407. this.forceProjectionMatrixCompute();
  40408. },
  40409. enumerable: true,
  40410. configurable: true
  40411. });
  40412. Object.defineProperty(PointLight.prototype, "direction", {
  40413. get: function () {
  40414. return this._direction;
  40415. },
  40416. /**
  40417. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40418. */
  40419. set: function (value) {
  40420. var previousNeedCube = this.needCube();
  40421. this._direction = value;
  40422. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40423. this._shadowGenerator.recreateShadowMap();
  40424. }
  40425. },
  40426. enumerable: true,
  40427. configurable: true
  40428. });
  40429. /**
  40430. * Returns the string "PointLight"
  40431. */
  40432. PointLight.prototype.getClassName = function () {
  40433. return "PointLight";
  40434. };
  40435. /**
  40436. * Returns the integer 0.
  40437. */
  40438. PointLight.prototype.getTypeID = function () {
  40439. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40440. };
  40441. /**
  40442. * Specifies wether or not the shadowmap should be a cube texture.
  40443. */
  40444. PointLight.prototype.needCube = function () {
  40445. return !this.direction;
  40446. };
  40447. /**
  40448. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40449. */
  40450. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40451. if (this.direction) {
  40452. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40453. }
  40454. else {
  40455. switch (faceIndex) {
  40456. case 0:
  40457. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40458. case 1:
  40459. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40460. case 2:
  40461. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40462. case 3:
  40463. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40464. case 4:
  40465. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40466. case 5:
  40467. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40468. }
  40469. }
  40470. return BABYLON.Vector3.Zero();
  40471. };
  40472. /**
  40473. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40474. * - fov = PI / 2
  40475. * - aspect ratio : 1.0
  40476. * - z-near and far equal to the active camera minZ and maxZ.
  40477. * Returns the PointLight.
  40478. */
  40479. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40480. var activeCamera = this.getScene().activeCamera;
  40481. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40482. };
  40483. PointLight.prototype._buildUniformLayout = function () {
  40484. this._uniformBuffer.addUniform("vLightData", 4);
  40485. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40486. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40487. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40488. this._uniformBuffer.create();
  40489. };
  40490. /**
  40491. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40492. * Returns the PointLight.
  40493. */
  40494. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40495. if (this.computeTransformedInformation()) {
  40496. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40497. return this;
  40498. }
  40499. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40500. return this;
  40501. };
  40502. return PointLight;
  40503. }(BABYLON.ShadowLight));
  40504. __decorate([
  40505. BABYLON.serialize()
  40506. ], PointLight.prototype, "shadowAngle", null);
  40507. BABYLON.PointLight = PointLight;
  40508. })(BABYLON || (BABYLON = {}));
  40509. //# sourceMappingURL=babylon.pointLight.js.map
  40510. /// <reference path="babylon.light.ts" />
  40511. var BABYLON;
  40512. (function (BABYLON) {
  40513. var DirectionalLight = (function (_super) {
  40514. __extends(DirectionalLight, _super);
  40515. /**
  40516. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40517. * The directional light is emitted from everywhere in the given direction.
  40518. * It can cast shawdows.
  40519. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40520. */
  40521. function DirectionalLight(name, direction, scene) {
  40522. var _this = _super.call(this, name, scene) || this;
  40523. _this._shadowFrustumSize = 0;
  40524. _this._shadowOrthoScale = 0.5;
  40525. _this.autoUpdateExtends = true;
  40526. // Cache
  40527. _this._orthoLeft = Number.MAX_VALUE;
  40528. _this._orthoRight = Number.MIN_VALUE;
  40529. _this._orthoTop = Number.MIN_VALUE;
  40530. _this._orthoBottom = Number.MAX_VALUE;
  40531. _this.position = direction.scale(-1.0);
  40532. _this.direction = direction;
  40533. return _this;
  40534. }
  40535. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40536. /**
  40537. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40538. */
  40539. get: function () {
  40540. return this._shadowFrustumSize;
  40541. },
  40542. /**
  40543. * Specifies a fix frustum size for the shadow generation.
  40544. */
  40545. set: function (value) {
  40546. this._shadowFrustumSize = value;
  40547. this.forceProjectionMatrixCompute();
  40548. },
  40549. enumerable: true,
  40550. configurable: true
  40551. });
  40552. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40553. get: function () {
  40554. return this._shadowOrthoScale;
  40555. },
  40556. set: function (value) {
  40557. this._shadowOrthoScale = value;
  40558. this.forceProjectionMatrixCompute();
  40559. },
  40560. enumerable: true,
  40561. configurable: true
  40562. });
  40563. /**
  40564. * Returns the string "DirectionalLight".
  40565. */
  40566. DirectionalLight.prototype.getClassName = function () {
  40567. return "DirectionalLight";
  40568. };
  40569. /**
  40570. * Returns the integer 1.
  40571. */
  40572. DirectionalLight.prototype.getTypeID = function () {
  40573. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40574. };
  40575. /**
  40576. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40577. * Returns the DirectionalLight Shadow projection matrix.
  40578. */
  40579. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40580. if (this.shadowFrustumSize > 0) {
  40581. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40582. }
  40583. else {
  40584. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40585. }
  40586. };
  40587. /**
  40588. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40589. * Returns the DirectionalLight Shadow projection matrix.
  40590. */
  40591. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40592. var activeCamera = this.getScene().activeCamera;
  40593. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40594. };
  40595. /**
  40596. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40597. * Returns the DirectionalLight Shadow projection matrix.
  40598. */
  40599. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40600. var activeCamera = this.getScene().activeCamera;
  40601. // Check extends
  40602. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40603. var tempVector3 = BABYLON.Vector3.Zero();
  40604. this._orthoLeft = Number.MAX_VALUE;
  40605. this._orthoRight = Number.MIN_VALUE;
  40606. this._orthoTop = Number.MIN_VALUE;
  40607. this._orthoBottom = Number.MAX_VALUE;
  40608. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40609. var mesh = renderList[meshIndex];
  40610. if (!mesh) {
  40611. continue;
  40612. }
  40613. var boundingInfo = mesh.getBoundingInfo();
  40614. if (!boundingInfo) {
  40615. continue;
  40616. }
  40617. var boundingBox = boundingInfo.boundingBox;
  40618. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40619. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40620. if (tempVector3.x < this._orthoLeft)
  40621. this._orthoLeft = tempVector3.x;
  40622. if (tempVector3.y < this._orthoBottom)
  40623. this._orthoBottom = tempVector3.y;
  40624. if (tempVector3.x > this._orthoRight)
  40625. this._orthoRight = tempVector3.x;
  40626. if (tempVector3.y > this._orthoTop)
  40627. this._orthoTop = tempVector3.y;
  40628. }
  40629. }
  40630. }
  40631. var xOffset = this._orthoRight - this._orthoLeft;
  40632. var yOffset = this._orthoTop - this._orthoBottom;
  40633. 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);
  40634. };
  40635. DirectionalLight.prototype._buildUniformLayout = function () {
  40636. this._uniformBuffer.addUniform("vLightData", 4);
  40637. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40638. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40639. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40640. this._uniformBuffer.create();
  40641. };
  40642. /**
  40643. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40644. * Returns the DirectionalLight.
  40645. */
  40646. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40647. if (this.computeTransformedInformation()) {
  40648. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40649. return this;
  40650. }
  40651. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40652. return this;
  40653. };
  40654. return DirectionalLight;
  40655. }(BABYLON.ShadowLight));
  40656. __decorate([
  40657. BABYLON.serialize()
  40658. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40659. __decorate([
  40660. BABYLON.serialize()
  40661. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40662. __decorate([
  40663. BABYLON.serialize()
  40664. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40665. BABYLON.DirectionalLight = DirectionalLight;
  40666. })(BABYLON || (BABYLON = {}));
  40667. //# sourceMappingURL=babylon.directionalLight.js.map
  40668. var BABYLON;
  40669. (function (BABYLON) {
  40670. var SpotLight = (function (_super) {
  40671. __extends(SpotLight, _super);
  40672. /**
  40673. * Creates a SpotLight object in the scene with the passed parameters :
  40674. * - `position` (Vector3) is the initial SpotLight position,
  40675. * - `direction` (Vector3) is the initial SpotLight direction,
  40676. * - `angle` (float, in radians) is the spot light cone angle,
  40677. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40678. * A spot light is a simply light oriented cone.
  40679. * It can cast shadows.
  40680. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40681. */
  40682. function SpotLight(name, position, direction, angle, exponent, scene) {
  40683. var _this = _super.call(this, name, scene) || this;
  40684. _this.position = position;
  40685. _this.direction = direction;
  40686. _this.angle = angle;
  40687. _this.exponent = exponent;
  40688. return _this;
  40689. }
  40690. Object.defineProperty(SpotLight.prototype, "angle", {
  40691. get: function () {
  40692. return this._angle;
  40693. },
  40694. set: function (value) {
  40695. this._angle = value;
  40696. this.forceProjectionMatrixCompute();
  40697. },
  40698. enumerable: true,
  40699. configurable: true
  40700. });
  40701. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40702. get: function () {
  40703. return this._shadowAngleScale;
  40704. },
  40705. /**
  40706. * Allows scaling the angle of the light for shadow generation only.
  40707. */
  40708. set: function (value) {
  40709. this._shadowAngleScale = value;
  40710. this.forceProjectionMatrixCompute();
  40711. },
  40712. enumerable: true,
  40713. configurable: true
  40714. });
  40715. /**
  40716. * Returns the string "SpotLight".
  40717. */
  40718. SpotLight.prototype.getClassName = function () {
  40719. return "SpotLight";
  40720. };
  40721. /**
  40722. * Returns the integer 2.
  40723. */
  40724. SpotLight.prototype.getTypeID = function () {
  40725. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40726. };
  40727. /**
  40728. * 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.
  40729. * Returns the SpotLight.
  40730. */
  40731. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40732. var activeCamera = this.getScene().activeCamera;
  40733. this._shadowAngleScale = this._shadowAngleScale || 1;
  40734. var angle = this._shadowAngleScale * this._angle;
  40735. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40736. };
  40737. SpotLight.prototype._buildUniformLayout = function () {
  40738. this._uniformBuffer.addUniform("vLightData", 4);
  40739. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40740. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40741. this._uniformBuffer.addUniform("vLightDirection", 3);
  40742. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40743. this._uniformBuffer.create();
  40744. };
  40745. /**
  40746. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40747. * Return the SpotLight.
  40748. */
  40749. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40750. var normalizeDirection;
  40751. if (this.computeTransformedInformation()) {
  40752. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40753. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40754. }
  40755. else {
  40756. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40757. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40758. }
  40759. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40760. return this;
  40761. };
  40762. return SpotLight;
  40763. }(BABYLON.ShadowLight));
  40764. __decorate([
  40765. BABYLON.serialize()
  40766. ], SpotLight.prototype, "angle", null);
  40767. __decorate([
  40768. BABYLON.serialize()
  40769. /**
  40770. * Allows scaling the angle of the light for shadow generation only.
  40771. */
  40772. ], SpotLight.prototype, "shadowAngleScale", null);
  40773. __decorate([
  40774. BABYLON.serialize()
  40775. ], SpotLight.prototype, "exponent", void 0);
  40776. BABYLON.SpotLight = SpotLight;
  40777. })(BABYLON || (BABYLON = {}));
  40778. //# sourceMappingURL=babylon.spotLight.js.map
  40779. var BABYLON;
  40780. (function (BABYLON) {
  40781. var PostProcess = (function () {
  40782. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  40783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  40784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40785. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  40786. if (blockCompilation === void 0) { blockCompilation = false; }
  40787. this.name = name;
  40788. this.width = -1;
  40789. this.height = -1;
  40790. this.autoClear = true;
  40791. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  40792. /*
  40793. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  40794. Can only be used on a single postprocess or on the last one of a chain.
  40795. */
  40796. this.enablePixelPerfectMode = false;
  40797. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  40798. this.alwaysForcePOT = false;
  40799. this.samples = 1;
  40800. this._reusable = false;
  40801. this._textures = new BABYLON.SmartArray(2);
  40802. this._currentRenderTextureInd = 0;
  40803. this._scaleRatio = new BABYLON.Vector2(1, 1);
  40804. this._texelSize = BABYLON.Vector2.Zero();
  40805. // Events
  40806. /**
  40807. * An event triggered when the postprocess is activated.
  40808. * @type {BABYLON.Observable}
  40809. */
  40810. this.onActivateObservable = new BABYLON.Observable();
  40811. /**
  40812. * An event triggered when the postprocess changes its size.
  40813. * @type {BABYLON.Observable}
  40814. */
  40815. this.onSizeChangedObservable = new BABYLON.Observable();
  40816. /**
  40817. * An event triggered when the postprocess applies its effect.
  40818. * @type {BABYLON.Observable}
  40819. */
  40820. this.onApplyObservable = new BABYLON.Observable();
  40821. /**
  40822. * An event triggered before rendering the postprocess
  40823. * @type {BABYLON.Observable}
  40824. */
  40825. this.onBeforeRenderObservable = new BABYLON.Observable();
  40826. /**
  40827. * An event triggered after rendering the postprocess
  40828. * @type {BABYLON.Observable}
  40829. */
  40830. this.onAfterRenderObservable = new BABYLON.Observable();
  40831. if (camera != null) {
  40832. this._camera = camera;
  40833. this._scene = camera.getScene();
  40834. camera.attachPostProcess(this);
  40835. this._engine = this._scene.getEngine();
  40836. }
  40837. else {
  40838. this._engine = engine;
  40839. }
  40840. this._options = options;
  40841. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  40842. this._reusable = reusable || false;
  40843. this._textureType = textureType;
  40844. this._samplers = samplers || [];
  40845. this._samplers.push("textureSampler");
  40846. this._fragmentUrl = fragmentUrl;
  40847. this._vertexUrl = vertexUrl;
  40848. this._parameters = parameters || [];
  40849. this._parameters.push("scale");
  40850. this._indexParameters = indexParameters;
  40851. if (!blockCompilation) {
  40852. this.updateEffect(defines);
  40853. }
  40854. }
  40855. Object.defineProperty(PostProcess.prototype, "onActivate", {
  40856. set: function (callback) {
  40857. if (this._onActivateObserver) {
  40858. this.onActivateObservable.remove(this._onActivateObserver);
  40859. }
  40860. this._onActivateObserver = this.onActivateObservable.add(callback);
  40861. },
  40862. enumerable: true,
  40863. configurable: true
  40864. });
  40865. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  40866. set: function (callback) {
  40867. if (this._onSizeChangedObserver) {
  40868. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  40869. }
  40870. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  40871. },
  40872. enumerable: true,
  40873. configurable: true
  40874. });
  40875. Object.defineProperty(PostProcess.prototype, "onApply", {
  40876. set: function (callback) {
  40877. if (this._onApplyObserver) {
  40878. this.onApplyObservable.remove(this._onApplyObserver);
  40879. }
  40880. this._onApplyObserver = this.onApplyObservable.add(callback);
  40881. },
  40882. enumerable: true,
  40883. configurable: true
  40884. });
  40885. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  40886. set: function (callback) {
  40887. if (this._onBeforeRenderObserver) {
  40888. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40889. }
  40890. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40891. },
  40892. enumerable: true,
  40893. configurable: true
  40894. });
  40895. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  40896. set: function (callback) {
  40897. if (this._onAfterRenderObserver) {
  40898. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40899. }
  40900. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40901. },
  40902. enumerable: true,
  40903. configurable: true
  40904. });
  40905. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  40906. get: function () {
  40907. return this._textures.data[this._currentRenderTextureInd];
  40908. },
  40909. set: function (value) {
  40910. this._forcedOutputTexture = value;
  40911. },
  40912. enumerable: true,
  40913. configurable: true
  40914. });
  40915. PostProcess.prototype.getCamera = function () {
  40916. return this._camera;
  40917. };
  40918. Object.defineProperty(PostProcess.prototype, "texelSize", {
  40919. get: function () {
  40920. if (this._shareOutputWithPostProcess) {
  40921. return this._shareOutputWithPostProcess.texelSize;
  40922. }
  40923. if (this._forcedOutputTexture) {
  40924. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  40925. }
  40926. return this._texelSize;
  40927. },
  40928. enumerable: true,
  40929. configurable: true
  40930. });
  40931. PostProcess.prototype.getEngine = function () {
  40932. return this._engine;
  40933. };
  40934. PostProcess.prototype.shareOutputWith = function (postProcess) {
  40935. this._disposeTextures();
  40936. this._shareOutputWithPostProcess = postProcess;
  40937. return this;
  40938. };
  40939. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  40940. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  40941. };
  40942. PostProcess.prototype.isReusable = function () {
  40943. return this._reusable;
  40944. };
  40945. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  40946. PostProcess.prototype.markTextureDirty = function () {
  40947. this.width = -1;
  40948. };
  40949. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  40950. var _this = this;
  40951. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  40952. camera = camera || this._camera;
  40953. var scene = camera.getScene();
  40954. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  40955. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  40956. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  40957. var desiredWidth = this._options.width || requiredWidth;
  40958. var desiredHeight = this._options.height || requiredHeight;
  40959. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  40960. if (!this._options.width) {
  40961. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  40962. }
  40963. if (!this._options.height) {
  40964. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  40965. }
  40966. }
  40967. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  40968. if (this._textures.length > 0) {
  40969. for (var i = 0; i < this._textures.length; i++) {
  40970. this._engine._releaseTexture(this._textures.data[i]);
  40971. }
  40972. this._textures.reset();
  40973. }
  40974. this.width = desiredWidth;
  40975. this.height = desiredHeight;
  40976. var textureSize = { width: this.width, height: this.height };
  40977. var textureOptions = {
  40978. generateMipMaps: false,
  40979. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  40980. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  40981. samplingMode: this.renderTargetSamplingMode,
  40982. type: this._textureType
  40983. };
  40984. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40985. if (this._reusable) {
  40986. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40987. }
  40988. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  40989. this.onSizeChangedObservable.notifyObservers(this);
  40990. }
  40991. this._textures.forEach(function (texture) {
  40992. if (texture.samples !== _this.samples) {
  40993. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  40994. }
  40995. });
  40996. }
  40997. var target;
  40998. if (this._shareOutputWithPostProcess) {
  40999. target = this._shareOutputWithPostProcess.outputTexture;
  41000. }
  41001. else if (this._forcedOutputTexture) {
  41002. target = this._forcedOutputTexture;
  41003. this.width = this._forcedOutputTexture._width;
  41004. this.height = this._forcedOutputTexture._height;
  41005. }
  41006. else {
  41007. target = this.outputTexture;
  41008. }
  41009. if (this.enablePixelPerfectMode) {
  41010. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  41011. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  41012. }
  41013. else {
  41014. this._scaleRatio.copyFromFloats(1, 1);
  41015. this._engine.bindFramebuffer(target);
  41016. }
  41017. this.onActivateObservable.notifyObservers(camera);
  41018. // Clear
  41019. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  41020. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  41021. }
  41022. if (this._reusable) {
  41023. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  41024. }
  41025. };
  41026. Object.defineProperty(PostProcess.prototype, "isSupported", {
  41027. get: function () {
  41028. return this._effect.isSupported;
  41029. },
  41030. enumerable: true,
  41031. configurable: true
  41032. });
  41033. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  41034. get: function () {
  41035. if (this._shareOutputWithPostProcess) {
  41036. return this._shareOutputWithPostProcess.aspectRatio;
  41037. }
  41038. if (this._forcedOutputTexture) {
  41039. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  41040. }
  41041. return this.width / this.height;
  41042. },
  41043. enumerable: true,
  41044. configurable: true
  41045. });
  41046. PostProcess.prototype.apply = function () {
  41047. // Check
  41048. if (!this._effect || !this._effect.isReady())
  41049. return null;
  41050. // States
  41051. this._engine.enableEffect(this._effect);
  41052. this._engine.setState(false);
  41053. this._engine.setDepthBuffer(false);
  41054. this._engine.setDepthWrite(false);
  41055. // Alpha
  41056. this._engine.setAlphaMode(this.alphaMode);
  41057. if (this.alphaConstants) {
  41058. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  41059. }
  41060. // Texture
  41061. var source;
  41062. if (this._shareOutputWithPostProcess) {
  41063. source = this._shareOutputWithPostProcess.outputTexture;
  41064. }
  41065. else if (this._forcedOutputTexture) {
  41066. source = this._forcedOutputTexture;
  41067. }
  41068. else {
  41069. source = this.outputTexture;
  41070. }
  41071. this._effect._bindTexture("textureSampler", source);
  41072. // Parameters
  41073. this._effect.setVector2("scale", this._scaleRatio);
  41074. this.onApplyObservable.notifyObservers(this._effect);
  41075. return this._effect;
  41076. };
  41077. PostProcess.prototype._disposeTextures = function () {
  41078. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  41079. return;
  41080. }
  41081. if (this._textures.length > 0) {
  41082. for (var i = 0; i < this._textures.length; i++) {
  41083. this._engine._releaseTexture(this._textures.data[i]);
  41084. }
  41085. }
  41086. this._textures.dispose();
  41087. };
  41088. PostProcess.prototype.dispose = function (camera) {
  41089. camera = camera || this._camera;
  41090. this._disposeTextures();
  41091. if (!camera) {
  41092. return;
  41093. }
  41094. camera.detachPostProcess(this);
  41095. var index = camera._postProcesses.indexOf(this);
  41096. if (index === 0 && camera._postProcesses.length > 0) {
  41097. this._camera._postProcesses[0].markTextureDirty();
  41098. }
  41099. this.onActivateObservable.clear();
  41100. this.onAfterRenderObservable.clear();
  41101. this.onApplyObservable.clear();
  41102. this.onBeforeRenderObservable.clear();
  41103. this.onSizeChangedObservable.clear();
  41104. };
  41105. return PostProcess;
  41106. }());
  41107. BABYLON.PostProcess = PostProcess;
  41108. })(BABYLON || (BABYLON = {}));
  41109. //# sourceMappingURL=babylon.postProcess.js.map
  41110. var BABYLON;
  41111. (function (BABYLON) {
  41112. var PassPostProcess = (function (_super) {
  41113. __extends(PassPostProcess, _super);
  41114. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41115. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41116. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41117. }
  41118. return PassPostProcess;
  41119. }(BABYLON.PostProcess));
  41120. BABYLON.PassPostProcess = PassPostProcess;
  41121. })(BABYLON || (BABYLON = {}));
  41122. //# sourceMappingURL=babylon.passPostProcess.js.map
  41123. var BABYLON;
  41124. (function (BABYLON) {
  41125. var BlurPostProcess = (function (_super) {
  41126. __extends(BlurPostProcess, _super);
  41127. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  41128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41129. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41130. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  41131. _this.direction = direction;
  41132. _this.onApplyObservable.add(function (effect) {
  41133. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  41134. });
  41135. _this.kernel = kernel;
  41136. return _this;
  41137. }
  41138. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  41139. /**
  41140. * Gets the length in pixels of the blur sample region
  41141. */
  41142. get: function () {
  41143. return this._idealKernel;
  41144. },
  41145. /**
  41146. * Sets the length in pixels of the blur sample region
  41147. */
  41148. set: function (v) {
  41149. if (this._idealKernel === v) {
  41150. return;
  41151. }
  41152. v = Math.max(v, 1);
  41153. this._idealKernel = v;
  41154. this._kernel = this._nearestBestKernel(v);
  41155. this._updateParameters();
  41156. },
  41157. enumerable: true,
  41158. configurable: true
  41159. });
  41160. BlurPostProcess.prototype._updateParameters = function () {
  41161. // Generate sampling offsets and weights
  41162. var N = this._kernel;
  41163. var centerIndex = (N - 1) / 2;
  41164. // Generate Gaussian sampling weights over kernel
  41165. var offsets = [];
  41166. var weights = [];
  41167. var totalWeight = 0;
  41168. for (var i = 0; i < N; i++) {
  41169. var u = i / (N - 1);
  41170. var w = this._gaussianWeight(u * 2.0 - 1);
  41171. offsets[i] = (i - centerIndex);
  41172. weights[i] = w;
  41173. totalWeight += w;
  41174. }
  41175. // Normalize weights
  41176. for (var i = 0; i < weights.length; i++) {
  41177. weights[i] /= totalWeight;
  41178. }
  41179. // Optimize: combine samples to take advantage of hardware linear sampling
  41180. // Walk from left to center, combining pairs (symmetrically)
  41181. var linearSamplingWeights = [];
  41182. var linearSamplingOffsets = [];
  41183. var linearSamplingMap = [];
  41184. for (var i = 0; i <= centerIndex; i += 2) {
  41185. var j = Math.min(i + 1, Math.floor(centerIndex));
  41186. var singleCenterSample = i === j;
  41187. if (singleCenterSample) {
  41188. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41189. }
  41190. else {
  41191. var sharedCell = j === centerIndex;
  41192. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  41193. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  41194. if (offsetLinear === 0) {
  41195. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41196. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  41197. }
  41198. else {
  41199. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  41200. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  41201. }
  41202. }
  41203. }
  41204. for (var i = 0; i < linearSamplingMap.length; i++) {
  41205. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  41206. linearSamplingWeights[i] = linearSamplingMap[i].w;
  41207. }
  41208. // Replace with optimized
  41209. offsets = linearSamplingOffsets;
  41210. weights = linearSamplingWeights;
  41211. // Generate shaders
  41212. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  41213. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  41214. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  41215. var defines = "";
  41216. for (var i = 0; i < varyingCount; i++) {
  41217. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  41218. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  41219. }
  41220. var depCount = 0;
  41221. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  41222. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  41223. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  41224. depCount++;
  41225. }
  41226. this.updateEffect(defines, null, null, {
  41227. varyingCount: varyingCount,
  41228. depCount: depCount
  41229. });
  41230. };
  41231. /**
  41232. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  41233. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41234. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41235. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41236. * The gaps between physical kernels are compensated for in the weighting of the samples
  41237. * @param idealKernel Ideal blur kernel.
  41238. * @return Nearest best kernel.
  41239. */
  41240. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41241. var v = Math.round(idealKernel);
  41242. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41243. var k = _a[_i];
  41244. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41245. return Math.max(k, 3);
  41246. }
  41247. }
  41248. return Math.max(v, 3);
  41249. };
  41250. /**
  41251. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41252. * @param x The point on the Gaussian distribution to sample.
  41253. * @return the value of the Gaussian function at x.
  41254. */
  41255. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41256. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41257. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41258. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41259. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41260. // truncated at around 1.3% of peak strength.
  41261. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41262. var sigma = (1 / 3);
  41263. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41264. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41265. var weight = (1.0 / denominator) * Math.exp(exponent);
  41266. return weight;
  41267. };
  41268. /**
  41269. * Generates a string that can be used as a floating point number in GLSL.
  41270. * @param x Value to print.
  41271. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41272. * @return GLSL float string.
  41273. */
  41274. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41275. if (decimalFigures === void 0) { decimalFigures = 8; }
  41276. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41277. };
  41278. return BlurPostProcess;
  41279. }(BABYLON.PostProcess));
  41280. BABYLON.BlurPostProcess = BlurPostProcess;
  41281. })(BABYLON || (BABYLON = {}));
  41282. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41283. var BABYLON;
  41284. (function (BABYLON) {
  41285. var FxaaPostProcess = (function (_super) {
  41286. __extends(FxaaPostProcess, _super);
  41287. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41288. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41289. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  41290. _this.onApplyObservable.add(function (effect) {
  41291. var texelSize = _this.texelSize;
  41292. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41293. });
  41294. return _this;
  41295. }
  41296. return FxaaPostProcess;
  41297. }(BABYLON.PostProcess));
  41298. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41299. })(BABYLON || (BABYLON = {}));
  41300. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41301. var BABYLON;
  41302. (function (BABYLON) {
  41303. var HighlightsPostProcess = (function (_super) {
  41304. __extends(HighlightsPostProcess, _super);
  41305. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41306. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41307. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41308. }
  41309. return HighlightsPostProcess;
  41310. }(BABYLON.PostProcess));
  41311. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41312. })(BABYLON || (BABYLON = {}));
  41313. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41314. var BABYLON;
  41315. (function (BABYLON) {
  41316. var ImageProcessingPostProcess = (function (_super) {
  41317. __extends(ImageProcessingPostProcess, _super);
  41318. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41319. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41320. var _this = _super.call(this, name, "imageProcessing", [
  41321. 'contrast',
  41322. 'vignetteSettings1',
  41323. 'vignetteSettings2',
  41324. 'cameraExposureLinear',
  41325. 'vCameraColorCurveNegative',
  41326. 'vCameraColorCurveNeutral',
  41327. 'vCameraColorCurvePositive',
  41328. 'colorTransformSettings'
  41329. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41330. _this.colorGradingWeight = 1.0;
  41331. _this.colorCurves = new BABYLON.ColorCurves();
  41332. _this._colorCurvesEnabled = true;
  41333. _this.cameraFov = 0.5;
  41334. _this.vignetteStretch = 0;
  41335. _this.vignetteCentreX = 0;
  41336. _this.vignetteCentreY = 0;
  41337. _this.vignetteWeight = 1.5;
  41338. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41339. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  41340. _this._vignetteEnabled = true;
  41341. _this.cameraContrast = 1.0;
  41342. _this.cameraExposure = 1.68;
  41343. _this._cameraToneMappingEnabled = true;
  41344. _this._fromLinearSpace = false;
  41345. _this._updateParameters();
  41346. _this.onApply = function (effect) {
  41347. var aspectRatio = _this.aspectRatio;
  41348. // Color
  41349. if (_this._colorCurvesEnabled) {
  41350. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  41351. }
  41352. if (_this._vignetteEnabled) {
  41353. // Vignette
  41354. var vignetteScaleY = Math.tan(_this.cameraFov * 0.5);
  41355. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41356. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41357. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  41358. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  41359. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  41360. var vignettePower = -2.0 * _this.vignetteWeight;
  41361. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  41362. }
  41363. // Contrast and exposure
  41364. effect.setFloat('contrast', _this.cameraContrast);
  41365. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposure) * Math.PI);
  41366. // Color transform settings
  41367. if (_this._colorGradingTexture) {
  41368. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  41369. var textureSize = _this.colorGradingTexture.getSize().height;
  41370. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41371. 0.5 / textureSize, // textureOffset
  41372. textureSize, // textureSize
  41373. _this.colorGradingWeight // weight
  41374. );
  41375. }
  41376. };
  41377. return _this;
  41378. }
  41379. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41380. get: function () {
  41381. return this._colorGradingTexture;
  41382. },
  41383. set: function (value) {
  41384. if (this._colorGradingTexture === value) {
  41385. return;
  41386. }
  41387. this._colorGradingTexture = value;
  41388. this._updateParameters();
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41394. get: function () {
  41395. return this._vignetteBlendMode;
  41396. },
  41397. set: function (value) {
  41398. if (this._vignetteBlendMode === value) {
  41399. return;
  41400. }
  41401. this._vignetteBlendMode = value;
  41402. this._updateParameters();
  41403. },
  41404. enumerable: true,
  41405. configurable: true
  41406. });
  41407. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41408. get: function () {
  41409. return this._colorCurvesEnabled;
  41410. },
  41411. set: function (value) {
  41412. if (this._colorCurvesEnabled === value) {
  41413. return;
  41414. }
  41415. this._colorCurvesEnabled = value;
  41416. this._updateParameters();
  41417. },
  41418. enumerable: true,
  41419. configurable: true
  41420. });
  41421. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41422. get: function () {
  41423. return this._vignetteEnabled;
  41424. },
  41425. set: function (value) {
  41426. if (this._vignetteEnabled === value) {
  41427. return;
  41428. }
  41429. this._vignetteEnabled = value;
  41430. this._updateParameters();
  41431. },
  41432. enumerable: true,
  41433. configurable: true
  41434. });
  41435. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41436. get: function () {
  41437. return this._fromLinearSpace;
  41438. },
  41439. set: function (value) {
  41440. if (this._fromLinearSpace === value) {
  41441. return;
  41442. }
  41443. this._fromLinearSpace = value;
  41444. this._updateParameters();
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  41450. get: function () {
  41451. return this._cameraToneMappingEnabled;
  41452. },
  41453. set: function (value) {
  41454. if (this._cameraToneMappingEnabled === value) {
  41455. return;
  41456. }
  41457. this._cameraToneMappingEnabled = value;
  41458. this._updateParameters();
  41459. },
  41460. enumerable: true,
  41461. configurable: true
  41462. });
  41463. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41464. var defines = "";
  41465. var samplers = ["textureSampler"];
  41466. if (this.colorGradingTexture) {
  41467. defines = "#define COLORGRADING\r\n";
  41468. samplers.push("txColorTransform");
  41469. }
  41470. if (this._vignetteEnabled) {
  41471. defines += "#define VIGNETTE\r\n";
  41472. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  41473. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  41474. }
  41475. else {
  41476. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  41477. }
  41478. }
  41479. if (this.cameraToneMappingEnabled) {
  41480. defines += "#define TONEMAPPING\r\n";
  41481. }
  41482. if (this._colorCurvesEnabled && this.colorCurves) {
  41483. defines += "#define COLORCURVES\r\n";
  41484. }
  41485. if (this._fromLinearSpace) {
  41486. defines += "#define FROMLINEARSPACE\r\n";
  41487. }
  41488. this.updateEffect(defines, null, samplers);
  41489. };
  41490. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  41491. get: function () {
  41492. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  41493. },
  41494. enumerable: true,
  41495. configurable: true
  41496. });
  41497. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  41498. get: function () {
  41499. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  41500. },
  41501. enumerable: true,
  41502. configurable: true
  41503. });
  41504. return ImageProcessingPostProcess;
  41505. }(BABYLON.PostProcess));
  41506. // Statics
  41507. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  41508. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  41509. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41510. })(BABYLON || (BABYLON = {}));
  41511. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41512. var BABYLON;
  41513. (function (BABYLON) {
  41514. /**
  41515. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41516. * It can help converting any input color in a desired output one. This can then be used to create effects
  41517. * from sepia, black and white to sixties or futuristic rendering...
  41518. *
  41519. * The only supported format is currently 3dl.
  41520. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41521. */
  41522. var ColorGradingTexture = (function (_super) {
  41523. __extends(ColorGradingTexture, _super);
  41524. /**
  41525. * Instantiates a ColorGradingTexture from the following parameters.
  41526. *
  41527. * @param url The location of the color gradind data (currently only supporting 3dl)
  41528. * @param scene The scene the texture will be used in
  41529. */
  41530. function ColorGradingTexture(url, scene) {
  41531. var _this = _super.call(this, scene) || this;
  41532. if (!url) {
  41533. return _this;
  41534. }
  41535. _this._textureMatrix = BABYLON.Matrix.Identity();
  41536. _this.name = url;
  41537. _this.url = url;
  41538. _this.hasAlpha = false;
  41539. _this.isCube = false;
  41540. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41541. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41542. _this.anisotropicFilteringLevel = 1;
  41543. _this._texture = _this._getFromCache(url, true);
  41544. if (!_this._texture) {
  41545. if (!scene.useDelayedTextureLoading) {
  41546. _this.loadTexture();
  41547. }
  41548. else {
  41549. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41550. }
  41551. }
  41552. return _this;
  41553. }
  41554. /**
  41555. * Returns the texture matrix used in most of the material.
  41556. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41557. */
  41558. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41559. return this._textureMatrix;
  41560. };
  41561. /**
  41562. * Occurs when the file being loaded is a .3dl LUT file.
  41563. */
  41564. ColorGradingTexture.prototype.load3dlTexture = function () {
  41565. var _this = this;
  41566. var mipLevels = 0;
  41567. var floatArrayView = null;
  41568. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41569. this._texture = texture;
  41570. var callback = function (text) {
  41571. var data;
  41572. var tempData;
  41573. var line;
  41574. var lines = text.split('\n');
  41575. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41576. var maxColor = 0;
  41577. for (var i = 0; i < lines.length; i++) {
  41578. line = lines[i];
  41579. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41580. continue;
  41581. if (line.indexOf('#') === 0)
  41582. continue;
  41583. var words = line.split(" ");
  41584. if (size === 0) {
  41585. // Number of space + one
  41586. size = words.length;
  41587. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41588. tempData = new Float32Array(size * size * size * 4);
  41589. continue;
  41590. }
  41591. if (size != 0) {
  41592. var r = Math.max(parseInt(words[0]), 0);
  41593. var g = Math.max(parseInt(words[1]), 0);
  41594. var b = Math.max(parseInt(words[2]), 0);
  41595. maxColor = Math.max(r, maxColor);
  41596. maxColor = Math.max(g, maxColor);
  41597. maxColor = Math.max(b, maxColor);
  41598. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41599. tempData[pixelStorageIndex + 0] = r;
  41600. tempData[pixelStorageIndex + 1] = g;
  41601. tempData[pixelStorageIndex + 2] = b;
  41602. tempData[pixelStorageIndex + 3] = 0;
  41603. pixelIndexSlice++;
  41604. if (pixelIndexSlice % size == 0) {
  41605. pixelIndexH++;
  41606. pixelIndexSlice = 0;
  41607. if (pixelIndexH % size == 0) {
  41608. pixelIndexW++;
  41609. pixelIndexH = 0;
  41610. }
  41611. }
  41612. }
  41613. }
  41614. for (var i = 0; i < tempData.length; i++) {
  41615. var value = tempData[i];
  41616. data[i] = (value / maxColor * 255);
  41617. }
  41618. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  41619. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41620. };
  41621. BABYLON.Tools.LoadFile(this.url, callback);
  41622. return this._texture;
  41623. };
  41624. /**
  41625. * Starts the loading process of the texture.
  41626. */
  41627. ColorGradingTexture.prototype.loadTexture = function () {
  41628. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41629. this.load3dlTexture();
  41630. }
  41631. };
  41632. /**
  41633. * Clones the color gradind texture.
  41634. */
  41635. ColorGradingTexture.prototype.clone = function () {
  41636. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41637. // Base texture
  41638. newTexture.level = this.level;
  41639. return newTexture;
  41640. };
  41641. /**
  41642. * Called during delayed load for textures.
  41643. */
  41644. ColorGradingTexture.prototype.delayLoad = function () {
  41645. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41646. return;
  41647. }
  41648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41649. this._texture = this._getFromCache(this.url, true);
  41650. if (!this._texture) {
  41651. this.loadTexture();
  41652. }
  41653. };
  41654. /**
  41655. * Binds the color grading to the shader.
  41656. * @param colorGrading The texture to bind
  41657. * @param effect The effect to bind to
  41658. */
  41659. ColorGradingTexture.Bind = function (colorGrading, effect) {
  41660. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  41661. var x = colorGrading.level; // Texture Level
  41662. var y = colorGrading.getSize().height; // Texture Size example with 8
  41663. var z = y - 1.0; // SizeMinusOne 8 - 1
  41664. var w = 1 / y; // Space of 1 slice 1 / 8
  41665. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  41666. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  41667. 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
  41668. 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
  41669. 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
  41670. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  41671. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  41672. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  41673. };
  41674. /**
  41675. * Prepare the list of uniforms associated with the ColorGrading effects.
  41676. * @param uniformsList The list of uniforms used in the effect
  41677. * @param samplersList The list of samplers used in the effect
  41678. */
  41679. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  41680. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  41681. samplersList.push("cameraColorGrading2DSampler");
  41682. };
  41683. /**
  41684. * Parses a color grading texture serialized by Babylon.
  41685. * @param parsedTexture The texture information being parsedTexture
  41686. * @param scene The scene to load the texture in
  41687. * @param rootUrl The root url of the data assets to load
  41688. * @return A color gradind texture
  41689. */
  41690. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41691. var texture = null;
  41692. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41693. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41694. texture.name = parsedTexture.name;
  41695. texture.level = parsedTexture.level;
  41696. }
  41697. return texture;
  41698. };
  41699. /**
  41700. * Serializes the LUT texture to json format.
  41701. */
  41702. ColorGradingTexture.prototype.serialize = function () {
  41703. if (!this.name) {
  41704. return null;
  41705. }
  41706. var serializationObject = {};
  41707. serializationObject.name = this.name;
  41708. serializationObject.level = this.level;
  41709. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41710. return serializationObject;
  41711. };
  41712. return ColorGradingTexture;
  41713. }(BABYLON.BaseTexture));
  41714. /**
  41715. * Empty line regex stored for GC.
  41716. */
  41717. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41718. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41719. })(BABYLON || (BABYLON = {}));
  41720. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41721. var BABYLON;
  41722. (function (BABYLON) {
  41723. /**
  41724. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41725. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41726. * 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;
  41727. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41728. */
  41729. var ColorCurves = (function () {
  41730. function ColorCurves() {
  41731. this._dirty = true;
  41732. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41733. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41734. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41735. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41736. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41737. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41738. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41739. this._globalHue = 30;
  41740. this._globalDensity = 0;
  41741. this._globalSaturation = 0;
  41742. this._globalExposure = 0;
  41743. this._highlightsHue = 30;
  41744. this._highlightsDensity = 0;
  41745. this._highlightsSaturation = 0;
  41746. this._highlightsExposure = 0;
  41747. this._midtonesHue = 30;
  41748. this._midtonesDensity = 0;
  41749. this._midtonesSaturation = 0;
  41750. this._midtonesExposure = 0;
  41751. this._shadowsHue = 30;
  41752. this._shadowsDensity = 0;
  41753. this._shadowsSaturation = 0;
  41754. this._shadowsExposure = 0;
  41755. }
  41756. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41757. /**
  41758. * Gets the global Hue value.
  41759. * 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).
  41760. */
  41761. get: function () {
  41762. return this._globalHue;
  41763. },
  41764. /**
  41765. * Sets the global Hue value.
  41766. * 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).
  41767. */
  41768. set: function (value) {
  41769. this._globalHue = value;
  41770. this._dirty = true;
  41771. },
  41772. enumerable: true,
  41773. configurable: true
  41774. });
  41775. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41776. /**
  41777. * Gets the global Density value.
  41778. * 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.
  41779. * Values less than zero provide a filter of opposite hue.
  41780. */
  41781. get: function () {
  41782. return this._globalDensity;
  41783. },
  41784. /**
  41785. * Sets the global Density value.
  41786. * 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.
  41787. * Values less than zero provide a filter of opposite hue.
  41788. */
  41789. set: function (value) {
  41790. this._globalDensity = value;
  41791. this._dirty = true;
  41792. },
  41793. enumerable: true,
  41794. configurable: true
  41795. });
  41796. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41797. /**
  41798. * Gets the global Saturation value.
  41799. * 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.
  41800. */
  41801. get: function () {
  41802. return this._globalSaturation;
  41803. },
  41804. /**
  41805. * Sets the global Saturation value.
  41806. * 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.
  41807. */
  41808. set: function (value) {
  41809. this._globalSaturation = value;
  41810. this._dirty = true;
  41811. },
  41812. enumerable: true,
  41813. configurable: true
  41814. });
  41815. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41816. /**
  41817. * Gets the highlights Hue value.
  41818. * 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).
  41819. */
  41820. get: function () {
  41821. return this._highlightsHue;
  41822. },
  41823. /**
  41824. * Sets the highlights Hue value.
  41825. * 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).
  41826. */
  41827. set: function (value) {
  41828. this._highlightsHue = value;
  41829. this._dirty = true;
  41830. },
  41831. enumerable: true,
  41832. configurable: true
  41833. });
  41834. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41835. /**
  41836. * Gets the highlights Density value.
  41837. * 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.
  41838. * Values less than zero provide a filter of opposite hue.
  41839. */
  41840. get: function () {
  41841. return this._highlightsDensity;
  41842. },
  41843. /**
  41844. * Sets the highlights Density value.
  41845. * 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.
  41846. * Values less than zero provide a filter of opposite hue.
  41847. */
  41848. set: function (value) {
  41849. this._highlightsDensity = value;
  41850. this._dirty = true;
  41851. },
  41852. enumerable: true,
  41853. configurable: true
  41854. });
  41855. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41856. /**
  41857. * Gets the highlights Saturation value.
  41858. * 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.
  41859. */
  41860. get: function () {
  41861. return this._highlightsSaturation;
  41862. },
  41863. /**
  41864. * Sets the highlights Saturation value.
  41865. * 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.
  41866. */
  41867. set: function (value) {
  41868. this._highlightsSaturation = value;
  41869. this._dirty = true;
  41870. },
  41871. enumerable: true,
  41872. configurable: true
  41873. });
  41874. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41875. /**
  41876. * Gets the highlights Exposure value.
  41877. * 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.
  41878. */
  41879. get: function () {
  41880. return this._highlightsExposure;
  41881. },
  41882. /**
  41883. * Sets the highlights Exposure value.
  41884. * 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.
  41885. */
  41886. set: function (value) {
  41887. this._highlightsExposure = value;
  41888. this._dirty = true;
  41889. },
  41890. enumerable: true,
  41891. configurable: true
  41892. });
  41893. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41894. /**
  41895. * Gets the midtones Hue value.
  41896. * 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).
  41897. */
  41898. get: function () {
  41899. return this._midtonesHue;
  41900. },
  41901. /**
  41902. * Sets the midtones Hue value.
  41903. * 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).
  41904. */
  41905. set: function (value) {
  41906. this._midtonesHue = value;
  41907. this._dirty = true;
  41908. },
  41909. enumerable: true,
  41910. configurable: true
  41911. });
  41912. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41913. /**
  41914. * Gets the midtones Density value.
  41915. * 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.
  41916. * Values less than zero provide a filter of opposite hue.
  41917. */
  41918. get: function () {
  41919. return this._midtonesDensity;
  41920. },
  41921. /**
  41922. * Sets the midtones Density value.
  41923. * 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.
  41924. * Values less than zero provide a filter of opposite hue.
  41925. */
  41926. set: function (value) {
  41927. this._midtonesDensity = value;
  41928. this._dirty = true;
  41929. },
  41930. enumerable: true,
  41931. configurable: true
  41932. });
  41933. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41934. /**
  41935. * Gets the midtones Saturation value.
  41936. * 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.
  41937. */
  41938. get: function () {
  41939. return this._midtonesSaturation;
  41940. },
  41941. /**
  41942. * Sets the midtones Saturation value.
  41943. * 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.
  41944. */
  41945. set: function (value) {
  41946. this._midtonesSaturation = value;
  41947. this._dirty = true;
  41948. },
  41949. enumerable: true,
  41950. configurable: true
  41951. });
  41952. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41953. /**
  41954. * Gets the midtones Exposure value.
  41955. * 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.
  41956. */
  41957. get: function () {
  41958. return this._midtonesExposure;
  41959. },
  41960. /**
  41961. * Sets the midtones Exposure value.
  41962. * 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.
  41963. */
  41964. set: function (value) {
  41965. this._midtonesExposure = value;
  41966. this._dirty = true;
  41967. },
  41968. enumerable: true,
  41969. configurable: true
  41970. });
  41971. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41972. /**
  41973. * Gets the shadows Hue value.
  41974. * 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).
  41975. */
  41976. get: function () {
  41977. return this._shadowsHue;
  41978. },
  41979. /**
  41980. * Sets the shadows Hue value.
  41981. * 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).
  41982. */
  41983. set: function (value) {
  41984. this._shadowsHue = value;
  41985. this._dirty = true;
  41986. },
  41987. enumerable: true,
  41988. configurable: true
  41989. });
  41990. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41991. /**
  41992. * Gets the shadows Density value.
  41993. * 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.
  41994. * Values less than zero provide a filter of opposite hue.
  41995. */
  41996. get: function () {
  41997. return this._shadowsDensity;
  41998. },
  41999. /**
  42000. * Sets the shadows Density value.
  42001. * 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.
  42002. * Values less than zero provide a filter of opposite hue.
  42003. */
  42004. set: function (value) {
  42005. this._shadowsDensity = value;
  42006. this._dirty = true;
  42007. },
  42008. enumerable: true,
  42009. configurable: true
  42010. });
  42011. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42012. /**
  42013. * Gets the shadows Saturation value.
  42014. * 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.
  42015. */
  42016. get: function () {
  42017. return this._shadowsSaturation;
  42018. },
  42019. /**
  42020. * Sets the shadows Saturation value.
  42021. * 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.
  42022. */
  42023. set: function (value) {
  42024. this._shadowsSaturation = value;
  42025. this._dirty = true;
  42026. },
  42027. enumerable: true,
  42028. configurable: true
  42029. });
  42030. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42031. /**
  42032. * Gets the shadows Exposure value.
  42033. * 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.
  42034. */
  42035. get: function () {
  42036. return this._shadowsExposure;
  42037. },
  42038. /**
  42039. * Sets the shadows Exposure value.
  42040. * 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.
  42041. */
  42042. set: function (value) {
  42043. this._shadowsExposure = value;
  42044. this._dirty = true;
  42045. },
  42046. enumerable: true,
  42047. configurable: true
  42048. });
  42049. /**
  42050. * Binds the color curves to the shader.
  42051. * @param colorCurves The color curve to bind
  42052. * @param effect The effect to bind to
  42053. */
  42054. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42055. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42056. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42057. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42058. if (colorCurves._dirty) {
  42059. colorCurves._dirty = false;
  42060. // Fill in global info.
  42061. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42062. // Compute highlights info.
  42063. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42064. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42065. // Compute midtones info.
  42066. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42067. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42068. // Compute shadows info.
  42069. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42070. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42071. // Compute deltas (neutral is midtones).
  42072. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42073. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42074. }
  42075. if (effect) {
  42076. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42077. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42078. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42079. }
  42080. };
  42081. /**
  42082. * Prepare the list of uniforms associated with the ColorCurves effects.
  42083. * @param uniformsList The list of uniforms used in the effect
  42084. */
  42085. ColorCurves.PrepareUniforms = function (uniformsList) {
  42086. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42087. };
  42088. /**
  42089. * Returns color grading data based on a hue, density, saturation and exposure value.
  42090. * @param filterHue The hue of the color filter.
  42091. * @param filterDensity The density of the color filter.
  42092. * @param saturation The saturation.
  42093. * @param exposure The exposure.
  42094. * @param result The result data container.
  42095. */
  42096. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42097. if (hue == null) {
  42098. return;
  42099. }
  42100. hue = ColorCurves.clamp(hue, 0, 360);
  42101. density = ColorCurves.clamp(density, -100, 100);
  42102. saturation = ColorCurves.clamp(saturation, -100, 100);
  42103. exposure = ColorCurves.clamp(exposure, -100, 100);
  42104. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42105. // so that the maximum filter density is only 50% control. This provides fine control
  42106. // for small values and reasonable range.
  42107. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42108. density *= 0.5;
  42109. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42110. if (density < 0) {
  42111. density *= -1;
  42112. hue = (hue + 180) % 360;
  42113. }
  42114. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42115. result.scaleToRef(2, result);
  42116. result.a = 1 + 0.01 * saturation;
  42117. };
  42118. /**
  42119. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42120. * @param value The input slider value in range [-100,100].
  42121. * @returns Adjusted value.
  42122. */
  42123. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42124. value /= 100;
  42125. var x = Math.abs(value);
  42126. x = Math.pow(x, 2);
  42127. if (value < 0) {
  42128. x *= -1;
  42129. }
  42130. x *= 100;
  42131. return x;
  42132. };
  42133. /**
  42134. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42135. * @param hue The hue (H) input.
  42136. * @param saturation The saturation (S) input.
  42137. * @param brightness The brightness (B) input.
  42138. * @result An RGBA color represented as Vector4.
  42139. */
  42140. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42141. var h = ColorCurves.clamp(hue, 0, 360);
  42142. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42143. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42144. if (s === 0) {
  42145. result.r = v;
  42146. result.g = v;
  42147. result.b = v;
  42148. }
  42149. else {
  42150. // sector 0 to 5
  42151. h /= 60;
  42152. var i = Math.floor(h);
  42153. // fractional part of h
  42154. var f = h - i;
  42155. var p = v * (1 - s);
  42156. var q = v * (1 - s * f);
  42157. var t = v * (1 - s * (1 - f));
  42158. switch (i) {
  42159. case 0:
  42160. result.r = v;
  42161. result.g = t;
  42162. result.b = p;
  42163. break;
  42164. case 1:
  42165. result.r = q;
  42166. result.g = v;
  42167. result.b = p;
  42168. break;
  42169. case 2:
  42170. result.r = p;
  42171. result.g = v;
  42172. result.b = t;
  42173. break;
  42174. case 3:
  42175. result.r = p;
  42176. result.g = q;
  42177. result.b = v;
  42178. break;
  42179. case 4:
  42180. result.r = t;
  42181. result.g = p;
  42182. result.b = v;
  42183. break;
  42184. default:
  42185. result.r = v;
  42186. result.g = p;
  42187. result.b = q;
  42188. break;
  42189. }
  42190. }
  42191. result.a = 1;
  42192. };
  42193. /**
  42194. * Returns a value clamped between min and max
  42195. * @param value The value to clamp
  42196. * @param min The minimum of value
  42197. * @param max The maximum of value
  42198. * @returns The clamped value.
  42199. */
  42200. ColorCurves.clamp = function (value, min, max) {
  42201. return Math.min(Math.max(value, min), max);
  42202. };
  42203. /**
  42204. * Clones the current color curve instance.
  42205. * @return The cloned curves
  42206. */
  42207. ColorCurves.prototype.clone = function () {
  42208. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42209. };
  42210. /**
  42211. * Serializes the current color curve instance to a json representation.
  42212. * @return a JSON representation
  42213. */
  42214. ColorCurves.prototype.serialize = function () {
  42215. return BABYLON.SerializationHelper.Serialize(this);
  42216. };
  42217. /**
  42218. * Parses the color curve from a json representation.
  42219. * @param source the JSON source to parse
  42220. * @return The parsed curves
  42221. */
  42222. ColorCurves.Parse = function (source) {
  42223. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42224. };
  42225. return ColorCurves;
  42226. }());
  42227. __decorate([
  42228. BABYLON.serialize()
  42229. ], ColorCurves.prototype, "_globalHue", void 0);
  42230. __decorate([
  42231. BABYLON.serialize()
  42232. ], ColorCurves.prototype, "_globalDensity", void 0);
  42233. __decorate([
  42234. BABYLON.serialize()
  42235. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42236. __decorate([
  42237. BABYLON.serialize()
  42238. ], ColorCurves.prototype, "_globalExposure", void 0);
  42239. __decorate([
  42240. BABYLON.serialize()
  42241. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42242. __decorate([
  42243. BABYLON.serialize()
  42244. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42245. __decorate([
  42246. BABYLON.serialize()
  42247. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42248. __decorate([
  42249. BABYLON.serialize()
  42250. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42251. __decorate([
  42252. BABYLON.serialize()
  42253. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42254. __decorate([
  42255. BABYLON.serialize()
  42256. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42257. __decorate([
  42258. BABYLON.serialize()
  42259. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42260. __decorate([
  42261. BABYLON.serialize()
  42262. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42263. BABYLON.ColorCurves = ColorCurves;
  42264. })(BABYLON || (BABYLON = {}));
  42265. //# sourceMappingURL=babylon.colorCurves.js.map
  42266. var BABYLON;
  42267. (function (BABYLON) {
  42268. var PostProcessRenderPipelineManager = (function () {
  42269. function PostProcessRenderPipelineManager() {
  42270. this._renderPipelines = {};
  42271. }
  42272. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42273. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42274. };
  42275. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42276. var renderPipeline = this._renderPipelines[renderPipelineName];
  42277. if (!renderPipeline) {
  42278. return;
  42279. }
  42280. renderPipeline._attachCameras(cameras, unique);
  42281. };
  42282. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42283. var renderPipeline = this._renderPipelines[renderPipelineName];
  42284. if (!renderPipeline) {
  42285. return;
  42286. }
  42287. renderPipeline._detachCameras(cameras);
  42288. };
  42289. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42290. var renderPipeline = this._renderPipelines[renderPipelineName];
  42291. if (!renderPipeline) {
  42292. return;
  42293. }
  42294. renderPipeline._enableEffect(renderEffectName, cameras);
  42295. };
  42296. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42297. var renderPipeline = this._renderPipelines[renderPipelineName];
  42298. if (!renderPipeline) {
  42299. return;
  42300. }
  42301. renderPipeline._disableEffect(renderEffectName, cameras);
  42302. };
  42303. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42304. var renderPipeline = this._renderPipelines[renderPipelineName];
  42305. if (!renderPipeline) {
  42306. return;
  42307. }
  42308. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42309. };
  42310. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42311. var renderPipeline = this._renderPipelines[renderPipelineName];
  42312. if (!renderPipeline) {
  42313. return;
  42314. }
  42315. renderPipeline._disableDisplayOnlyPass(cameras);
  42316. };
  42317. PostProcessRenderPipelineManager.prototype.update = function () {
  42318. for (var renderPipelineName in this._renderPipelines) {
  42319. var pipeline = this._renderPipelines[renderPipelineName];
  42320. if (!pipeline.isSupported) {
  42321. pipeline.dispose();
  42322. delete this._renderPipelines[renderPipelineName];
  42323. }
  42324. else {
  42325. pipeline._update();
  42326. }
  42327. }
  42328. };
  42329. return PostProcessRenderPipelineManager;
  42330. }());
  42331. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42332. })(BABYLON || (BABYLON = {}));
  42333. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42334. var BABYLON;
  42335. (function (BABYLON) {
  42336. var PostProcessRenderPass = (function () {
  42337. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42338. this._enabled = true;
  42339. this._refCount = 0;
  42340. this._name = name;
  42341. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42342. this.setRenderList(renderList);
  42343. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42344. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42345. this._scene = scene;
  42346. this._renderList = renderList;
  42347. }
  42348. // private
  42349. PostProcessRenderPass.prototype._incRefCount = function () {
  42350. if (this._refCount === 0) {
  42351. this._scene.customRenderTargets.push(this._renderTexture);
  42352. }
  42353. return ++this._refCount;
  42354. };
  42355. PostProcessRenderPass.prototype._decRefCount = function () {
  42356. this._refCount--;
  42357. if (this._refCount <= 0) {
  42358. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42359. }
  42360. return this._refCount;
  42361. };
  42362. PostProcessRenderPass.prototype._update = function () {
  42363. this.setRenderList(this._renderList);
  42364. };
  42365. // public
  42366. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42367. this._renderTexture.renderList = renderList;
  42368. };
  42369. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42370. return this._renderTexture;
  42371. };
  42372. return PostProcessRenderPass;
  42373. }());
  42374. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42375. })(BABYLON || (BABYLON = {}));
  42376. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42377. var BABYLON;
  42378. (function (BABYLON) {
  42379. var PostProcessRenderEffect = (function () {
  42380. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42381. this._engine = engine;
  42382. this._name = name;
  42383. this._singleInstance = singleInstance || true;
  42384. this._getPostProcess = getPostProcess;
  42385. this._cameras = [];
  42386. this._indicesForCamera = [];
  42387. this._postProcesses = {};
  42388. this._renderPasses = {};
  42389. this._renderEffectAsPasses = {};
  42390. }
  42391. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42392. get: function () {
  42393. for (var index in this._postProcesses) {
  42394. if (!this._postProcesses[index].isSupported) {
  42395. return false;
  42396. }
  42397. }
  42398. return true;
  42399. },
  42400. enumerable: true,
  42401. configurable: true
  42402. });
  42403. PostProcessRenderEffect.prototype._update = function () {
  42404. for (var renderPassName in this._renderPasses) {
  42405. this._renderPasses[renderPassName]._update();
  42406. }
  42407. };
  42408. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42409. this._renderPasses[renderPass._name] = renderPass;
  42410. this._linkParameters();
  42411. };
  42412. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42413. delete this._renderPasses[renderPass._name];
  42414. this._linkParameters();
  42415. };
  42416. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42417. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42418. this._linkParameters();
  42419. };
  42420. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42421. for (var renderPassName in this._renderPasses) {
  42422. if (renderPassName === passName) {
  42423. return this._renderPasses[passName];
  42424. }
  42425. }
  42426. };
  42427. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42428. this._renderPasses = {};
  42429. this._linkParameters();
  42430. };
  42431. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42432. var cameraKey;
  42433. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42434. for (var i = 0; i < _cam.length; i++) {
  42435. var camera = _cam[i];
  42436. var cameraName = camera.name;
  42437. if (this._singleInstance) {
  42438. cameraKey = 0;
  42439. }
  42440. else {
  42441. cameraKey = cameraName;
  42442. }
  42443. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42444. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42445. if (!this._indicesForCamera[cameraName]) {
  42446. this._indicesForCamera[cameraName] = [];
  42447. }
  42448. this._indicesForCamera[cameraName].push(index);
  42449. if (this._cameras.indexOf(camera) === -1) {
  42450. this._cameras[cameraName] = camera;
  42451. }
  42452. for (var passName in this._renderPasses) {
  42453. this._renderPasses[passName]._incRefCount();
  42454. }
  42455. }
  42456. this._linkParameters();
  42457. };
  42458. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42459. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42460. for (var i = 0; i < _cam.length; i++) {
  42461. var camera = _cam[i];
  42462. var cameraName = camera.name;
  42463. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42464. var index = this._cameras.indexOf(cameraName);
  42465. this._indicesForCamera.splice(index, 1);
  42466. this._cameras.splice(index, 1);
  42467. for (var passName in this._renderPasses) {
  42468. this._renderPasses[passName]._decRefCount();
  42469. }
  42470. }
  42471. };
  42472. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42473. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42474. for (var i = 0; i < _cam.length; i++) {
  42475. var camera = _cam[i];
  42476. var cameraName = camera.name;
  42477. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42478. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42479. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42480. }
  42481. }
  42482. for (var passName in this._renderPasses) {
  42483. this._renderPasses[passName]._incRefCount();
  42484. }
  42485. }
  42486. };
  42487. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42488. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42489. for (var i = 0; i < _cam.length; i++) {
  42490. var camera = _cam[i];
  42491. var cameraName = camera.Name;
  42492. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42493. for (var passName in this._renderPasses) {
  42494. this._renderPasses[passName]._decRefCount();
  42495. }
  42496. }
  42497. };
  42498. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42499. if (this._singleInstance) {
  42500. return this._postProcesses[0];
  42501. }
  42502. else {
  42503. return this._postProcesses[camera.name];
  42504. }
  42505. };
  42506. PostProcessRenderEffect.prototype._linkParameters = function () {
  42507. var _this = this;
  42508. for (var index in this._postProcesses) {
  42509. if (this.applyParameters) {
  42510. this.applyParameters(this._postProcesses[index]);
  42511. }
  42512. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42513. _this._linkTextures(effect);
  42514. });
  42515. }
  42516. };
  42517. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42518. for (var renderPassName in this._renderPasses) {
  42519. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42520. }
  42521. for (var renderEffectName in this._renderEffectAsPasses) {
  42522. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42523. }
  42524. };
  42525. return PostProcessRenderEffect;
  42526. }());
  42527. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42528. })(BABYLON || (BABYLON = {}));
  42529. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42530. var BABYLON;
  42531. (function (BABYLON) {
  42532. var PostProcessRenderPipeline = (function () {
  42533. function PostProcessRenderPipeline(engine, name) {
  42534. this._engine = engine;
  42535. this._name = name;
  42536. this._renderEffects = new Array();
  42537. this._renderEffectsForIsolatedPass = new Array();
  42538. this._cameras = [];
  42539. }
  42540. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42541. get: function () {
  42542. for (var renderEffectName in this._renderEffects) {
  42543. if (!this._renderEffects[renderEffectName].isSupported) {
  42544. return false;
  42545. }
  42546. }
  42547. return true;
  42548. },
  42549. enumerable: true,
  42550. configurable: true
  42551. });
  42552. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42553. this._renderEffects[renderEffect._name] = renderEffect;
  42554. };
  42555. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42556. var renderEffects = this._renderEffects[renderEffectName];
  42557. if (!renderEffects) {
  42558. return;
  42559. }
  42560. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42561. };
  42562. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42563. var renderEffects = this._renderEffects[renderEffectName];
  42564. if (!renderEffects) {
  42565. return;
  42566. }
  42567. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42568. };
  42569. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42570. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42571. var indicesToDelete = [];
  42572. var i;
  42573. for (i = 0; i < _cam.length; i++) {
  42574. var camera = _cam[i];
  42575. var cameraName = camera.name;
  42576. if (this._cameras.indexOf(camera) === -1) {
  42577. this._cameras[cameraName] = camera;
  42578. }
  42579. else if (unique) {
  42580. indicesToDelete.push(i);
  42581. }
  42582. }
  42583. for (i = 0; i < indicesToDelete.length; i++) {
  42584. cameras.splice(indicesToDelete[i], 1);
  42585. }
  42586. for (var renderEffectName in this._renderEffects) {
  42587. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42588. }
  42589. };
  42590. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42591. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42592. for (var renderEffectName in this._renderEffects) {
  42593. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42594. }
  42595. for (var i = 0; i < _cam.length; i++) {
  42596. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42597. }
  42598. };
  42599. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42600. var _this = this;
  42601. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42602. var pass = null;
  42603. var renderEffectName;
  42604. for (renderEffectName in this._renderEffects) {
  42605. pass = this._renderEffects[renderEffectName].getPass(passName);
  42606. if (pass != null) {
  42607. break;
  42608. }
  42609. }
  42610. if (pass === null) {
  42611. return;
  42612. }
  42613. for (renderEffectName in this._renderEffects) {
  42614. this._renderEffects[renderEffectName]._disable(_cam);
  42615. }
  42616. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42617. for (var i = 0; i < _cam.length; i++) {
  42618. var camera = _cam[i];
  42619. var cameraName = camera.name;
  42620. 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); });
  42621. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42622. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42623. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42624. }
  42625. };
  42626. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42627. var _this = this;
  42628. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42629. for (var i = 0; i < _cam.length; i++) {
  42630. var camera = _cam[i];
  42631. var cameraName = camera.name;
  42632. 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); });
  42633. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42634. }
  42635. for (var renderEffectName in this._renderEffects) {
  42636. this._renderEffects[renderEffectName]._enable(_cam);
  42637. }
  42638. };
  42639. PostProcessRenderPipeline.prototype._update = function () {
  42640. for (var renderEffectName in this._renderEffects) {
  42641. this._renderEffects[renderEffectName]._update();
  42642. }
  42643. for (var i = 0; i < this._cameras.length; i++) {
  42644. var cameraName = this._cameras[i].name;
  42645. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42646. this._renderEffectsForIsolatedPass[cameraName]._update();
  42647. }
  42648. }
  42649. };
  42650. PostProcessRenderPipeline.prototype._reset = function () {
  42651. this._renderEffects = new Array();
  42652. this._renderEffectsForIsolatedPass = new Array();
  42653. };
  42654. PostProcessRenderPipeline.prototype.dispose = function () {
  42655. // Must be implemented by children
  42656. };
  42657. return PostProcessRenderPipeline;
  42658. }());
  42659. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42660. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42661. __decorate([
  42662. BABYLON.serialize()
  42663. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42664. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42665. })(BABYLON || (BABYLON = {}));
  42666. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42667. var BABYLON;
  42668. (function (BABYLON) {
  42669. var DefaultRenderingPipeline = (function (_super) {
  42670. __extends(DefaultRenderingPipeline, _super);
  42671. /**
  42672. * @constructor
  42673. * @param {string} name - The rendering pipeline name
  42674. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42675. * @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)
  42676. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42677. */
  42678. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  42679. var _this = _super.call(this, scene.getEngine(), name) || this;
  42680. _this.PassPostProcessId = "PassPostProcessEffect";
  42681. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42682. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42683. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42684. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42685. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42686. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42687. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42688. // IAnimatable
  42689. _this.animations = [];
  42690. // Values
  42691. _this._bloomEnabled = false;
  42692. _this._fxaaEnabled = false;
  42693. _this._imageProcessingEnabled = true;
  42694. _this._bloomScale = 0.6;
  42695. /**
  42696. * Specifies the size of the bloom blur kernel, relative to the final output size
  42697. */
  42698. _this.bloomKernel = 64;
  42699. /**
  42700. * Specifies the weight of the bloom in the final rendering
  42701. */
  42702. _this._bloomWeight = 0.15;
  42703. _this._cameras = cameras || [];
  42704. // Initialize
  42705. _this._hdr = hdr;
  42706. _this._scene = scene;
  42707. // Misc
  42708. _this._defaultPipelineTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42709. // Attach
  42710. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42711. _this._buildPipeline();
  42712. return _this;
  42713. }
  42714. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42715. get: function () {
  42716. return this._bloomWeight;
  42717. },
  42718. set: function (value) {
  42719. if (this._bloomWeight === value) {
  42720. return;
  42721. }
  42722. this._bloomWeight = value;
  42723. if (this._hdr && this.copyBack) {
  42724. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42725. }
  42726. },
  42727. enumerable: true,
  42728. configurable: true
  42729. });
  42730. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42731. get: function () {
  42732. return this._bloomScale;
  42733. },
  42734. set: function (value) {
  42735. if (this._bloomScale === value) {
  42736. return;
  42737. }
  42738. this._bloomScale = value;
  42739. this._buildPipeline();
  42740. },
  42741. enumerable: true,
  42742. configurable: true
  42743. });
  42744. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42745. get: function () {
  42746. return this._bloomEnabled;
  42747. },
  42748. set: function (enabled) {
  42749. if (this._bloomEnabled === enabled) {
  42750. return;
  42751. }
  42752. this._bloomEnabled = enabled;
  42753. this._buildPipeline();
  42754. },
  42755. enumerable: true,
  42756. configurable: true
  42757. });
  42758. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42759. get: function () {
  42760. return this._fxaaEnabled;
  42761. },
  42762. set: function (enabled) {
  42763. if (this._fxaaEnabled === enabled) {
  42764. return;
  42765. }
  42766. this._fxaaEnabled = enabled;
  42767. this._buildPipeline();
  42768. },
  42769. enumerable: true,
  42770. configurable: true
  42771. });
  42772. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42773. get: function () {
  42774. return this._imageProcessingEnabled;
  42775. },
  42776. set: function (enabled) {
  42777. if (this._imageProcessingEnabled === enabled) {
  42778. return;
  42779. }
  42780. this._imageProcessingEnabled = enabled;
  42781. this._buildPipeline();
  42782. },
  42783. enumerable: true,
  42784. configurable: true
  42785. });
  42786. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42787. var _this = this;
  42788. var engine = this._scene.getEngine();
  42789. this._disposePostProcesses();
  42790. this._reset();
  42791. if (this.bloomEnabled) {
  42792. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42793. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42794. if (!this._hdr) {
  42795. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42796. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42797. this.highlights.autoClear = false;
  42798. this.highlights.alwaysForcePOT = true;
  42799. }
  42800. 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);
  42801. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42802. this.blurX.alwaysForcePOT = true;
  42803. this.blurX.autoClear = false;
  42804. this.blurX.onActivateObservable.add(function () {
  42805. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42806. _this.blurX.kernel = _this.bloomKernel * dw;
  42807. });
  42808. 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);
  42809. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42810. this.blurY.alwaysForcePOT = true;
  42811. this.blurY.autoClear = false;
  42812. this.blurY.onActivateObservable.add(function () {
  42813. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42814. _this.blurY.kernel = _this.bloomKernel * dh;
  42815. });
  42816. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42817. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42818. this.copyBack.alwaysForcePOT = true;
  42819. if (this._hdr) {
  42820. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42821. var w = this.bloomWeight;
  42822. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42823. }
  42824. else {
  42825. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42826. }
  42827. this.copyBack.autoClear = false;
  42828. }
  42829. if (this._imageProcessingEnabled) {
  42830. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42831. if (this._hdr) {
  42832. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42833. }
  42834. }
  42835. if (this.fxaaEnabled) {
  42836. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42837. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42838. this.fxaa.autoClear = !this.bloomEnabled && !this.imageProcessing;
  42839. }
  42840. else {
  42841. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42842. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42843. this.finalMerge.autoClear = !this.bloomEnabled && !this.imageProcessing;
  42844. }
  42845. if (this.bloomEnabled) {
  42846. if (this._hdr) {
  42847. this.copyBack.shareOutputWith(this.blurX);
  42848. if (this.imageProcessing) {
  42849. this.imageProcessing.shareOutputWith(this.pass);
  42850. this.imageProcessing.autoClear = false;
  42851. }
  42852. else if (this.fxaa) {
  42853. this.fxaa.shareOutputWith(this.pass);
  42854. }
  42855. else {
  42856. this.finalMerge.shareOutputWith(this.pass);
  42857. }
  42858. }
  42859. else {
  42860. if (this.fxaa) {
  42861. this.fxaa.shareOutputWith(this.pass);
  42862. }
  42863. else {
  42864. this.finalMerge.shareOutputWith(this.pass);
  42865. }
  42866. }
  42867. }
  42868. if (this._cameras !== null) {
  42869. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42870. }
  42871. };
  42872. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42873. for (var i = 0; i < this._cameras.length; i++) {
  42874. var camera = this._cameras[i];
  42875. if (this.pass) {
  42876. this.pass.dispose(camera);
  42877. this.pass = null;
  42878. }
  42879. if (this.highlights) {
  42880. this.highlights.dispose(camera);
  42881. this.highlights = null;
  42882. }
  42883. if (this.blurX) {
  42884. this.blurX.dispose(camera);
  42885. this.blurX = null;
  42886. }
  42887. if (this.blurY) {
  42888. this.blurY.dispose(camera);
  42889. this.blurY = null;
  42890. }
  42891. if (this.copyBack) {
  42892. this.copyBack.dispose(camera);
  42893. this.copyBack = null;
  42894. }
  42895. if (this.imageProcessing) {
  42896. this.imageProcessing.dispose(camera);
  42897. this.imageProcessing = null;
  42898. }
  42899. if (this.fxaa) {
  42900. this.fxaa.dispose(camera);
  42901. this.fxaa = null;
  42902. }
  42903. if (this.finalMerge) {
  42904. this.finalMerge.dispose(camera);
  42905. this.finalMerge = null;
  42906. }
  42907. }
  42908. };
  42909. // Dispose
  42910. DefaultRenderingPipeline.prototype.dispose = function () {
  42911. this._disposePostProcesses();
  42912. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  42913. _super.prototype.dispose.call(this);
  42914. };
  42915. // Serialize rendering pipeline
  42916. DefaultRenderingPipeline.prototype.serialize = function () {
  42917. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42918. serializationObject.customType = "DefaultRenderingPipeline";
  42919. return serializationObject;
  42920. };
  42921. // Parse serialized pipeline
  42922. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  42923. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  42924. };
  42925. return DefaultRenderingPipeline;
  42926. }(BABYLON.PostProcessRenderPipeline));
  42927. __decorate([
  42928. BABYLON.serialize()
  42929. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  42930. __decorate([
  42931. BABYLON.serialize()
  42932. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  42933. __decorate([
  42934. BABYLON.serialize()
  42935. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  42936. __decorate([
  42937. BABYLON.serialize()
  42938. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  42939. __decorate([
  42940. BABYLON.serialize()
  42941. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  42942. __decorate([
  42943. BABYLON.serialize()
  42944. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  42945. __decorate([
  42946. BABYLON.serialize()
  42947. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  42948. __decorate([
  42949. BABYLON.serialize()
  42950. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  42951. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  42952. })(BABYLON || (BABYLON = {}));
  42953. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  42954. BABYLON.Effect.ShadersStore={"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<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n#ifdef LDROUTPUT\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","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}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\n}","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}"};
  42955. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\nreturn esm;\n}\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","kernelBlurFragment":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  42956. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  42957. module.exports = BABYLON;
  42958. };