babylon.max.js 2.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694
  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. function serializeAsColor4(sourceName) {
  4816. return generateSerializableMember(8, sourceName); // color 4
  4817. }
  4818. BABYLON.serializeAsColor4 = serializeAsColor4;
  4819. function serializeAsImageProcessingConfiguration(sourceName) {
  4820. return generateSerializableMember(9, sourceName); // image processing
  4821. }
  4822. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4823. var SerializationHelper = (function () {
  4824. function SerializationHelper() {
  4825. }
  4826. SerializationHelper.Serialize = function (entity, serializationObject) {
  4827. if (!serializationObject) {
  4828. serializationObject = {};
  4829. }
  4830. // Tags
  4831. if (BABYLON.Tags) {
  4832. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4833. }
  4834. // Properties
  4835. for (var property in entity.__serializableMembers) {
  4836. var propertyDescriptor = entity.__serializableMembers[property];
  4837. var targetPropertyName = propertyDescriptor.sourceName || property;
  4838. var propertyType = propertyDescriptor.type;
  4839. var sourceProperty = entity[property];
  4840. if (sourceProperty !== undefined && sourceProperty !== null) {
  4841. switch (propertyType) {
  4842. case 0:
  4843. serializationObject[targetPropertyName] = sourceProperty;
  4844. break;
  4845. case 1:
  4846. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4847. break;
  4848. case 2:
  4849. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4850. break;
  4851. case 3:
  4852. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4853. break;
  4854. case 4:
  4855. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4856. break;
  4857. case 5:
  4858. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4859. break;
  4860. case 6:
  4861. serializationObject[targetPropertyName] = sourceProperty.id;
  4862. break;
  4863. case 7:
  4864. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4865. break;
  4866. case 8:
  4867. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4868. break;
  4869. case 9:
  4870. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. return serializationObject;
  4876. };
  4877. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4878. var destination = creationFunction();
  4879. // Tags
  4880. if (BABYLON.Tags) {
  4881. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4882. }
  4883. // Properties
  4884. for (var property in destination.__serializableMembers) {
  4885. var propertyDescriptor = destination.__serializableMembers[property];
  4886. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4887. var propertyType = propertyDescriptor.type;
  4888. if (sourceProperty !== undefined && sourceProperty !== null) {
  4889. switch (propertyType) {
  4890. case 0:
  4891. destination[property] = sourceProperty;
  4892. break;
  4893. case 1:
  4894. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4895. break;
  4896. case 2:
  4897. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4898. break;
  4899. case 3:
  4900. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4901. break;
  4902. case 4:
  4903. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4904. break;
  4905. case 5:
  4906. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4907. break;
  4908. case 6:
  4909. destination[property] = scene.getLastMeshByID(sourceProperty);
  4910. break;
  4911. case 7:
  4912. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4913. break;
  4914. case 8:
  4915. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4916. break;
  4917. case 9:
  4918. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4919. break;
  4920. }
  4921. }
  4922. }
  4923. return destination;
  4924. };
  4925. SerializationHelper.Clone = function (creationFunction, source) {
  4926. var destination = creationFunction();
  4927. // Tags
  4928. if (BABYLON.Tags) {
  4929. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4930. }
  4931. // Properties
  4932. for (var property in destination.__serializableMembers) {
  4933. var propertyDescriptor = destination.__serializableMembers[property];
  4934. var sourceProperty = source[property];
  4935. var propertyType = propertyDescriptor.type;
  4936. if (sourceProperty !== undefined && sourceProperty !== null) {
  4937. switch (propertyType) {
  4938. case 0: // Value
  4939. case 6:
  4940. destination[property] = sourceProperty;
  4941. break;
  4942. case 1: // Texture
  4943. case 2: // Color3
  4944. case 3: // FresnelParameters
  4945. case 4: // Vector2
  4946. case 5: // Vector3
  4947. case 7:
  4948. destination[property] = sourceProperty.clone();
  4949. break;
  4950. }
  4951. }
  4952. }
  4953. return destination;
  4954. };
  4955. return SerializationHelper;
  4956. }());
  4957. BABYLON.SerializationHelper = SerializationHelper;
  4958. })(BABYLON || (BABYLON = {}));
  4959. //# sourceMappingURL=babylon.decorators.js.map
  4960. var BABYLON;
  4961. (function (BABYLON) {
  4962. /**
  4963. * A class serves as a medium between the observable and its observers
  4964. */
  4965. var EventState = (function () {
  4966. /**
  4967. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4968. */
  4969. function EventState(mask, skipNextObservers) {
  4970. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4971. this.initalize(mask, skipNextObservers);
  4972. }
  4973. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4974. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4975. this.mask = mask;
  4976. this.skipNextObservers = skipNextObservers;
  4977. return this;
  4978. };
  4979. return EventState;
  4980. }());
  4981. BABYLON.EventState = EventState;
  4982. /**
  4983. * Represent an Observer registered to a given Observable object.
  4984. */
  4985. var Observer = (function () {
  4986. function Observer(callback, mask) {
  4987. this.callback = callback;
  4988. this.mask = mask;
  4989. }
  4990. return Observer;
  4991. }());
  4992. BABYLON.Observer = Observer;
  4993. /**
  4994. * The Observable class is a simple implementation of the Observable pattern.
  4995. * 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.
  4996. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4997. * 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).
  4998. * 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.
  4999. */
  5000. var Observable = (function () {
  5001. function Observable() {
  5002. this._observers = new Array();
  5003. this._eventState = new EventState(0);
  5004. }
  5005. /**
  5006. * Create a new Observer with the specified callback
  5007. * @param callback the callback that will be executed for that Observer
  5008. * @param mask the mask used to filter observers
  5009. * @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.
  5010. */
  5011. Observable.prototype.add = function (callback, mask, insertFirst) {
  5012. if (mask === void 0) { mask = -1; }
  5013. if (insertFirst === void 0) { insertFirst = false; }
  5014. if (!callback) {
  5015. return null;
  5016. }
  5017. var observer = new Observer(callback, mask);
  5018. if (insertFirst) {
  5019. this._observers.unshift(observer);
  5020. }
  5021. else {
  5022. this._observers.push(observer);
  5023. }
  5024. return observer;
  5025. };
  5026. /**
  5027. * Remove an Observer from the Observable object
  5028. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5029. */
  5030. Observable.prototype.remove = function (observer) {
  5031. var index = this._observers.indexOf(observer);
  5032. if (index !== -1) {
  5033. this._observers.splice(index, 1);
  5034. return true;
  5035. }
  5036. return false;
  5037. };
  5038. /**
  5039. * Remove a callback from the Observable object
  5040. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5041. */
  5042. Observable.prototype.removeCallback = function (callback) {
  5043. for (var index = 0; index < this._observers.length; index++) {
  5044. if (this._observers[index].callback === callback) {
  5045. this._observers.splice(index, 1);
  5046. return true;
  5047. }
  5048. }
  5049. return false;
  5050. };
  5051. /**
  5052. * Notify all Observers by calling their respective callback with the given data
  5053. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5054. * @param eventData
  5055. * @param mask
  5056. */
  5057. Observable.prototype.notifyObservers = function (eventData, mask) {
  5058. if (mask === void 0) { mask = -1; }
  5059. var state = this._eventState;
  5060. state.mask = mask;
  5061. state.skipNextObservers = false;
  5062. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5063. var obs = _a[_i];
  5064. if (obs.mask & mask) {
  5065. obs.callback(eventData, state);
  5066. }
  5067. if (state.skipNextObservers) {
  5068. return false;
  5069. }
  5070. }
  5071. return true;
  5072. };
  5073. /**
  5074. * return true is the Observable has at least one Observer registered
  5075. */
  5076. Observable.prototype.hasObservers = function () {
  5077. return this._observers.length > 0;
  5078. };
  5079. /**
  5080. * Clear the list of observers
  5081. */
  5082. Observable.prototype.clear = function () {
  5083. this._observers = new Array();
  5084. };
  5085. /**
  5086. * Clone the current observable
  5087. */
  5088. Observable.prototype.clone = function () {
  5089. var result = new Observable();
  5090. result._observers = this._observers.slice(0);
  5091. return result;
  5092. };
  5093. /**
  5094. * Does this observable handles observer registered with a given mask
  5095. * @param {number} trigger - the mask to be tested
  5096. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5097. **/
  5098. Observable.prototype.hasSpecificMask = function (mask) {
  5099. if (mask === void 0) { mask = -1; }
  5100. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5101. var obs = _a[_i];
  5102. if (obs.mask & mask && obs.mask === mask) {
  5103. return true;
  5104. }
  5105. }
  5106. return false;
  5107. };
  5108. return Observable;
  5109. }());
  5110. BABYLON.Observable = Observable;
  5111. })(BABYLON || (BABYLON = {}));
  5112. //# sourceMappingURL=babylon.observable.js.map
  5113. var BABYLON;
  5114. (function (BABYLON) {
  5115. var SmartArray = (function () {
  5116. function SmartArray(capacity) {
  5117. this.length = 0;
  5118. this._duplicateId = 0;
  5119. this.data = new Array(capacity);
  5120. this._id = SmartArray._GlobalId++;
  5121. }
  5122. SmartArray.prototype.push = function (value) {
  5123. this.data[this.length++] = value;
  5124. if (this.length > this.data.length) {
  5125. this.data.length *= 2;
  5126. }
  5127. if (!value.__smartArrayFlags) {
  5128. value.__smartArrayFlags = {};
  5129. }
  5130. value.__smartArrayFlags[this._id] = this._duplicateId;
  5131. };
  5132. SmartArray.prototype.forEach = function (func) {
  5133. for (var index = 0; index < this.length; index++) {
  5134. func(this.data[index]);
  5135. }
  5136. };
  5137. SmartArray.prototype.pushNoDuplicate = function (value) {
  5138. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5139. return false;
  5140. }
  5141. this.push(value);
  5142. return true;
  5143. };
  5144. SmartArray.prototype.sort = function (compareFn) {
  5145. this.data.sort(compareFn);
  5146. };
  5147. SmartArray.prototype.reset = function () {
  5148. this.length = 0;
  5149. this._duplicateId++;
  5150. };
  5151. SmartArray.prototype.dispose = function () {
  5152. this.reset();
  5153. this.data.length = 0;
  5154. };
  5155. SmartArray.prototype.concat = function (array) {
  5156. if (array.length === 0) {
  5157. return;
  5158. }
  5159. if (this.length + array.length > this.data.length) {
  5160. this.data.length = (this.length + array.length) * 2;
  5161. }
  5162. for (var index = 0; index < array.length; index++) {
  5163. this.data[this.length++] = (array.data || array)[index];
  5164. }
  5165. };
  5166. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5167. if (array.length === 0) {
  5168. return;
  5169. }
  5170. if (this.length + array.length > this.data.length) {
  5171. this.data.length = (this.length + array.length) * 2;
  5172. }
  5173. for (var index = 0; index < array.length; index++) {
  5174. var item = (array.data || array)[index];
  5175. this.pushNoDuplicate(item);
  5176. }
  5177. };
  5178. SmartArray.prototype.indexOf = function (value) {
  5179. var position = this.data.indexOf(value);
  5180. if (position >= this.length) {
  5181. return -1;
  5182. }
  5183. return position;
  5184. };
  5185. SmartArray.prototype.contains = function (value) {
  5186. return this.data.indexOf(value) !== -1;
  5187. };
  5188. return SmartArray;
  5189. }());
  5190. // Statics
  5191. SmartArray._GlobalId = 0;
  5192. BABYLON.SmartArray = SmartArray;
  5193. })(BABYLON || (BABYLON = {}));
  5194. //# sourceMappingURL=babylon.smartArray.js.map
  5195. var BABYLON;
  5196. (function (BABYLON) {
  5197. // Screenshots
  5198. var screenshotCanvas;
  5199. var cloneValue = function (source, destinationObject) {
  5200. if (!source)
  5201. return null;
  5202. if (source instanceof BABYLON.Mesh) {
  5203. return null;
  5204. }
  5205. if (source instanceof BABYLON.SubMesh) {
  5206. return source.clone(destinationObject);
  5207. }
  5208. else if (source.clone) {
  5209. return source.clone();
  5210. }
  5211. return null;
  5212. };
  5213. var Tools = (function () {
  5214. function Tools() {
  5215. }
  5216. ;
  5217. /**
  5218. * Interpolates between a and b via alpha
  5219. * @param a The lower value (returned when alpha = 0)
  5220. * @param b The upper value (returned when alpha = 1)
  5221. * @param alpha The interpolation-factor
  5222. * @return The mixed value
  5223. */
  5224. Tools.Mix = function (a, b, alpha) {
  5225. return a * (1 - alpha) + b * alpha;
  5226. };
  5227. Tools.Instantiate = function (className) {
  5228. var arr = className.split(".");
  5229. var fn = (window || this);
  5230. for (var i = 0, len = arr.length; i < len; i++) {
  5231. fn = fn[arr[i]];
  5232. }
  5233. if (typeof fn !== "function") {
  5234. return null;
  5235. }
  5236. return fn;
  5237. };
  5238. Tools.SetImmediate = function (action) {
  5239. if (window.setImmediate) {
  5240. window.setImmediate(action);
  5241. }
  5242. else {
  5243. setTimeout(action, 1);
  5244. }
  5245. };
  5246. Tools.IsExponentOfTwo = function (value) {
  5247. var count = 1;
  5248. do {
  5249. count *= 2;
  5250. } while (count < value);
  5251. return count === value;
  5252. };
  5253. /**
  5254. * Find the next highest power of two.
  5255. * @param x Number to start search from.
  5256. * @return Next highest power of two.
  5257. */
  5258. Tools.CeilingPOT = function (x) {
  5259. x--;
  5260. x |= x >> 1;
  5261. x |= x >> 2;
  5262. x |= x >> 4;
  5263. x |= x >> 8;
  5264. x |= x >> 16;
  5265. x++;
  5266. return x;
  5267. };
  5268. /**
  5269. * Find the next lowest power of two.
  5270. * @param x Number to start search from.
  5271. * @return Next lowest power of two.
  5272. */
  5273. Tools.FloorPOT = function (x) {
  5274. x = x | (x >> 1);
  5275. x = x | (x >> 2);
  5276. x = x | (x >> 4);
  5277. x = x | (x >> 8);
  5278. x = x | (x >> 16);
  5279. return x - (x >> 1);
  5280. };
  5281. /**
  5282. * Find the nearest power of two.
  5283. * @param x Number to start search from.
  5284. * @return Next nearest power of two.
  5285. */
  5286. Tools.NearestPOT = function (x) {
  5287. var c = Tools.CeilingPOT(x);
  5288. var f = Tools.FloorPOT(x);
  5289. return (c - x) > (x - f) ? f : c;
  5290. };
  5291. Tools.GetExponentOfTwo = function (value, max, mode) {
  5292. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5293. var pot;
  5294. switch (mode) {
  5295. case BABYLON.Engine.SCALEMODE_FLOOR:
  5296. pot = Tools.FloorPOT(value);
  5297. break;
  5298. case BABYLON.Engine.SCALEMODE_NEAREST:
  5299. pot = Tools.NearestPOT(value);
  5300. break;
  5301. case BABYLON.Engine.SCALEMODE_CEILING:
  5302. pot = Tools.CeilingPOT(value);
  5303. break;
  5304. }
  5305. return Math.min(pot, max);
  5306. };
  5307. Tools.GetFilename = function (path) {
  5308. var index = path.lastIndexOf("/");
  5309. if (index < 0)
  5310. return path;
  5311. return path.substring(index + 1);
  5312. };
  5313. Tools.GetDOMTextContent = function (element) {
  5314. var result = "";
  5315. var child = element.firstChild;
  5316. while (child) {
  5317. if (child.nodeType === 3) {
  5318. result += child.textContent;
  5319. }
  5320. child = child.nextSibling;
  5321. }
  5322. return result;
  5323. };
  5324. Tools.ToDegrees = function (angle) {
  5325. return angle * 180 / Math.PI;
  5326. };
  5327. Tools.ToRadians = function (angle) {
  5328. return angle * Math.PI / 180;
  5329. };
  5330. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5331. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5332. var output = "";
  5333. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5334. var i = 0;
  5335. var bytes = new Uint8Array(buffer);
  5336. while (i < bytes.length) {
  5337. chr1 = bytes[i++];
  5338. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5339. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5340. enc1 = chr1 >> 2;
  5341. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5342. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5343. enc4 = chr3 & 63;
  5344. if (isNaN(chr2)) {
  5345. enc3 = enc4 = 64;
  5346. }
  5347. else if (isNaN(chr3)) {
  5348. enc4 = 64;
  5349. }
  5350. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5351. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5352. }
  5353. return "data:image/png;base64," + output;
  5354. };
  5355. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5356. if (bias === void 0) { bias = null; }
  5357. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5358. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5359. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5360. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5361. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5362. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5363. }
  5364. if (bias) {
  5365. minimum.x -= minimum.x * bias.x + bias.y;
  5366. minimum.y -= minimum.y * bias.x + bias.y;
  5367. minimum.z -= minimum.z * bias.x + bias.y;
  5368. maximum.x += maximum.x * bias.x + bias.y;
  5369. maximum.y += maximum.y * bias.x + bias.y;
  5370. maximum.z += maximum.z * bias.x + bias.y;
  5371. }
  5372. return {
  5373. minimum: minimum,
  5374. maximum: maximum
  5375. };
  5376. };
  5377. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5378. if (bias === void 0) { bias = null; }
  5379. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5380. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5381. if (!stride) {
  5382. stride = 3;
  5383. }
  5384. for (var index = start; index < start + count; index++) {
  5385. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5386. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5387. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5388. }
  5389. if (bias) {
  5390. minimum.x -= minimum.x * bias.x + bias.y;
  5391. minimum.y -= minimum.y * bias.x + bias.y;
  5392. minimum.z -= minimum.z * bias.x + bias.y;
  5393. maximum.x += maximum.x * bias.x + bias.y;
  5394. maximum.y += maximum.y * bias.x + bias.y;
  5395. maximum.z += maximum.z * bias.x + bias.y;
  5396. }
  5397. return {
  5398. minimum: minimum,
  5399. maximum: maximum
  5400. };
  5401. };
  5402. Tools.Vector2ArrayFeeder = function (array) {
  5403. return function (index) {
  5404. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5405. var length = isFloatArray ? array.length / 2 : array.length;
  5406. if (index >= length) {
  5407. return null;
  5408. }
  5409. if (isFloatArray) {
  5410. var fa = array;
  5411. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5412. }
  5413. var a = array;
  5414. return a[index];
  5415. };
  5416. };
  5417. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5418. if (bias === void 0) { bias = null; }
  5419. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5420. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5421. var i = 0;
  5422. var cur = feeder(i++);
  5423. while (cur) {
  5424. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5425. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5426. cur = feeder(i++);
  5427. }
  5428. if (bias) {
  5429. minimum.x -= minimum.x * bias.x + bias.y;
  5430. minimum.y -= minimum.y * bias.x + bias.y;
  5431. maximum.x += maximum.x * bias.x + bias.y;
  5432. maximum.y += maximum.y * bias.x + bias.y;
  5433. }
  5434. return {
  5435. minimum: minimum,
  5436. maximum: maximum
  5437. };
  5438. };
  5439. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5440. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5441. return undefined;
  5442. return Array.isArray(obj) ? obj : [obj];
  5443. };
  5444. // Misc.
  5445. Tools.GetPointerPrefix = function () {
  5446. var eventPrefix = "pointer";
  5447. // Check if pointer events are supported
  5448. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5449. eventPrefix = "mouse";
  5450. }
  5451. return eventPrefix;
  5452. };
  5453. /**
  5454. * @param func - the function to be called
  5455. * @param requester - the object that will request the next frame. Falls back to window.
  5456. */
  5457. Tools.QueueNewFrame = function (func, requester) {
  5458. if (requester === void 0) { requester = window; }
  5459. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5460. /*if(requester.isPresenting) {
  5461. return;
  5462. } else*/ if (requester.requestAnimationFrame)
  5463. requester.requestAnimationFrame(func);
  5464. else if (requester.msRequestAnimationFrame)
  5465. requester.msRequestAnimationFrame(func);
  5466. else if (requester.webkitRequestAnimationFrame)
  5467. requester.webkitRequestAnimationFrame(func);
  5468. else if (requester.mozRequestAnimationFrame)
  5469. requester.mozRequestAnimationFrame(func);
  5470. else if (requester.oRequestAnimationFrame)
  5471. requester.oRequestAnimationFrame(func);
  5472. else {
  5473. window.setTimeout(func, 16);
  5474. }
  5475. };
  5476. Tools.RequestFullscreen = function (element) {
  5477. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5478. if (!requestFunction)
  5479. return;
  5480. requestFunction.call(element);
  5481. };
  5482. Tools.ExitFullscreen = function () {
  5483. if (document.exitFullscreen) {
  5484. document.exitFullscreen();
  5485. }
  5486. else if (document.mozCancelFullScreen) {
  5487. document.mozCancelFullScreen();
  5488. }
  5489. else if (document.webkitCancelFullScreen) {
  5490. document.webkitCancelFullScreen();
  5491. }
  5492. else if (document.msCancelFullScreen) {
  5493. document.msCancelFullScreen();
  5494. }
  5495. };
  5496. Tools.SetCorsBehavior = function (url, img) {
  5497. if (Tools.CorsBehavior) {
  5498. switch (typeof (Tools.CorsBehavior)) {
  5499. case "function":
  5500. var result = Tools.CorsBehavior(url);
  5501. if (result) {
  5502. img.crossOrigin = result;
  5503. }
  5504. break;
  5505. case "string":
  5506. default:
  5507. img.crossOrigin = Tools.CorsBehavior;
  5508. break;
  5509. }
  5510. }
  5511. };
  5512. // External files
  5513. Tools.CleanUrl = function (url) {
  5514. url = url.replace(/#/mg, "%23");
  5515. return url;
  5516. };
  5517. Tools.LoadImage = function (url, onload, onerror, database) {
  5518. if (url instanceof ArrayBuffer) {
  5519. url = Tools.EncodeArrayBufferTobase64(url);
  5520. }
  5521. url = Tools.CleanUrl(url);
  5522. var img = new Image();
  5523. if (url.substr(0, 5) !== "data:") {
  5524. Tools.SetCorsBehavior(url, img);
  5525. }
  5526. img.onload = function () {
  5527. onload(img);
  5528. };
  5529. img.onerror = function (err) {
  5530. Tools.Error("Error while trying to load image: " + url);
  5531. if (Tools.UseFallbackTexture) {
  5532. img.src = Tools.fallbackTexture;
  5533. onload(img);
  5534. }
  5535. else {
  5536. onerror();
  5537. }
  5538. };
  5539. var noIndexedDB = function () {
  5540. img.src = url;
  5541. };
  5542. var loadFromIndexedDB = function () {
  5543. database.loadImageFromDB(url, img);
  5544. };
  5545. //ANY database to do!
  5546. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5547. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5548. }
  5549. else {
  5550. if (url.indexOf("file:") !== 0) {
  5551. noIndexedDB();
  5552. }
  5553. else {
  5554. var textureName = url.substring(5).toLowerCase();
  5555. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5556. try {
  5557. var blobURL;
  5558. try {
  5559. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5560. }
  5561. catch (ex) {
  5562. // Chrome doesn't support oneTimeOnly parameter
  5563. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5564. }
  5565. img.src = blobURL;
  5566. }
  5567. catch (e) {
  5568. img.src = null;
  5569. }
  5570. }
  5571. else {
  5572. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5573. img.src = Tools.fallbackTexture;
  5574. }
  5575. }
  5576. }
  5577. return img;
  5578. };
  5579. //ANY
  5580. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5581. url = Tools.CleanUrl(url);
  5582. var noIndexedDB = function () {
  5583. var request = new XMLHttpRequest();
  5584. var loadUrl = Tools.BaseUrl + url;
  5585. request.open('GET', loadUrl, true);
  5586. if (useArrayBuffer) {
  5587. request.responseType = "arraybuffer";
  5588. }
  5589. request.onprogress = progressCallBack;
  5590. request.onreadystatechange = function () {
  5591. // In case of undefined state in some browsers.
  5592. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5593. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5594. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5595. callback(!useArrayBuffer ? request.responseText : request.response);
  5596. }
  5597. else {
  5598. if (onError) {
  5599. onError(request);
  5600. }
  5601. else {
  5602. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5603. }
  5604. }
  5605. }
  5606. };
  5607. request.send(null);
  5608. };
  5609. var loadFromIndexedDB = function () {
  5610. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5611. };
  5612. if (url.indexOf("file:") !== -1) {
  5613. var fileName = url.substring(5).toLowerCase();
  5614. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5615. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5616. }
  5617. else {
  5618. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5619. }
  5620. }
  5621. else {
  5622. // Caching all files
  5623. if (database && database.enableSceneOffline) {
  5624. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5625. }
  5626. else {
  5627. noIndexedDB();
  5628. }
  5629. }
  5630. };
  5631. /**
  5632. * Load a script (identified by an url). When the url returns, the
  5633. * content of this file is added into a new script element, attached to the DOM (body element)
  5634. */
  5635. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5636. var head = document.getElementsByTagName('head')[0];
  5637. var script = document.createElement('script');
  5638. script.type = 'text/javascript';
  5639. script.src = scriptUrl;
  5640. var self = this;
  5641. script.onload = function () {
  5642. if (onSuccess) {
  5643. onSuccess();
  5644. }
  5645. };
  5646. script.onerror = function () {
  5647. if (onError) {
  5648. onError();
  5649. }
  5650. };
  5651. head.appendChild(script);
  5652. };
  5653. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5654. var reader = new FileReader();
  5655. reader.onload = function (e) {
  5656. //target doesn't have result from ts 1.3
  5657. callback(e.target['result']);
  5658. };
  5659. reader.onprogress = progressCallback;
  5660. reader.readAsDataURL(fileToLoad);
  5661. };
  5662. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5663. var reader = new FileReader();
  5664. reader.onerror = function (e) {
  5665. Tools.Log("Error while reading file: " + fileToLoad.name);
  5666. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5667. };
  5668. reader.onload = function (e) {
  5669. //target doesn't have result from ts 1.3
  5670. callback(e.target['result']);
  5671. };
  5672. reader.onprogress = progressCallBack;
  5673. if (!useArrayBuffer) {
  5674. // Asynchronous read
  5675. reader.readAsText(fileToLoad);
  5676. }
  5677. else {
  5678. reader.readAsArrayBuffer(fileToLoad);
  5679. }
  5680. };
  5681. //returns a downloadable url to a file content.
  5682. Tools.FileAsURL = function (content) {
  5683. var fileBlob = new Blob([content]);
  5684. var url = window.URL || window.webkitURL;
  5685. var link = url.createObjectURL(fileBlob);
  5686. return link;
  5687. };
  5688. // Misc.
  5689. Tools.Format = function (value, decimals) {
  5690. if (decimals === void 0) { decimals = 2; }
  5691. return value.toFixed(decimals);
  5692. };
  5693. Tools.CheckExtends = function (v, min, max) {
  5694. if (v.x < min.x)
  5695. min.x = v.x;
  5696. if (v.y < min.y)
  5697. min.y = v.y;
  5698. if (v.z < min.z)
  5699. min.z = v.z;
  5700. if (v.x > max.x)
  5701. max.x = v.x;
  5702. if (v.y > max.y)
  5703. max.y = v.y;
  5704. if (v.z > max.z)
  5705. max.z = v.z;
  5706. };
  5707. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5708. for (var prop in source) {
  5709. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5710. continue;
  5711. }
  5712. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5713. continue;
  5714. }
  5715. var sourceValue = source[prop];
  5716. var typeOfSourceValue = typeof sourceValue;
  5717. if (typeOfSourceValue === "function") {
  5718. continue;
  5719. }
  5720. if (typeOfSourceValue === "object") {
  5721. if (sourceValue instanceof Array) {
  5722. destination[prop] = [];
  5723. if (sourceValue.length > 0) {
  5724. if (typeof sourceValue[0] == "object") {
  5725. for (var index = 0; index < sourceValue.length; index++) {
  5726. var clonedValue = cloneValue(sourceValue[index], destination);
  5727. if (destination[prop].indexOf(clonedValue) === -1) {
  5728. destination[prop].push(clonedValue);
  5729. }
  5730. }
  5731. }
  5732. else {
  5733. destination[prop] = sourceValue.slice(0);
  5734. }
  5735. }
  5736. }
  5737. else {
  5738. destination[prop] = cloneValue(sourceValue, destination);
  5739. }
  5740. }
  5741. else {
  5742. destination[prop] = sourceValue;
  5743. }
  5744. }
  5745. };
  5746. Tools.IsEmpty = function (obj) {
  5747. for (var i in obj) {
  5748. return false;
  5749. }
  5750. return true;
  5751. };
  5752. Tools.RegisterTopRootEvents = function (events) {
  5753. for (var index = 0; index < events.length; index++) {
  5754. var event = events[index];
  5755. window.addEventListener(event.name, event.handler, false);
  5756. try {
  5757. if (window.parent) {
  5758. window.parent.addEventListener(event.name, event.handler, false);
  5759. }
  5760. }
  5761. catch (e) {
  5762. // Silently fails...
  5763. }
  5764. }
  5765. };
  5766. Tools.UnregisterTopRootEvents = function (events) {
  5767. for (var index = 0; index < events.length; index++) {
  5768. var event = events[index];
  5769. window.removeEventListener(event.name, event.handler);
  5770. try {
  5771. if (window.parent) {
  5772. window.parent.removeEventListener(event.name, event.handler);
  5773. }
  5774. }
  5775. catch (e) {
  5776. // Silently fails...
  5777. }
  5778. }
  5779. };
  5780. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5781. if (mimeType === void 0) { mimeType = "image/png"; }
  5782. // Read the contents of the framebuffer
  5783. var numberOfChannelsByLine = width * 4;
  5784. var halfHeight = height / 2;
  5785. //Reading datas from WebGL
  5786. var data = engine.readPixels(0, 0, width, height);
  5787. //To flip image on Y axis.
  5788. for (var i = 0; i < halfHeight; i++) {
  5789. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5790. var currentCell = j + i * numberOfChannelsByLine;
  5791. var targetLine = height - i - 1;
  5792. var targetCell = j + targetLine * numberOfChannelsByLine;
  5793. var temp = data[currentCell];
  5794. data[currentCell] = data[targetCell];
  5795. data[targetCell] = temp;
  5796. }
  5797. }
  5798. // Create a 2D canvas to store the result
  5799. if (!screenshotCanvas) {
  5800. screenshotCanvas = document.createElement('canvas');
  5801. }
  5802. screenshotCanvas.width = width;
  5803. screenshotCanvas.height = height;
  5804. var context = screenshotCanvas.getContext('2d');
  5805. // Copy the pixels to a 2D canvas
  5806. var imageData = context.createImageData(width, height);
  5807. var castData = (imageData.data);
  5808. castData.set(data);
  5809. context.putImageData(imageData, 0, 0);
  5810. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5811. };
  5812. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5813. if (mimeType === void 0) { mimeType = "image/png"; }
  5814. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5815. if (successCallback) {
  5816. successCallback(base64Image);
  5817. }
  5818. else {
  5819. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5820. if (("download" in document.createElement("a"))) {
  5821. var a = window.document.createElement("a");
  5822. a.href = base64Image;
  5823. var date = new Date();
  5824. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5825. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5826. window.document.body.appendChild(a);
  5827. a.addEventListener("click", function () {
  5828. a.parentElement.removeChild(a);
  5829. });
  5830. a.click();
  5831. //Or opening a new tab with the image if it is not possible to automatically start download.
  5832. }
  5833. else {
  5834. var newWindow = window.open("");
  5835. var img = newWindow.document.createElement("img");
  5836. img.src = base64Image;
  5837. newWindow.document.body.appendChild(img);
  5838. }
  5839. }
  5840. };
  5841. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5842. if (mimeType === void 0) { mimeType = "image/png"; }
  5843. var width;
  5844. var height;
  5845. // If a precision value is specified
  5846. if (size.precision) {
  5847. width = Math.round(engine.getRenderWidth() * size.precision);
  5848. height = Math.round(width / engine.getAspectRatio(camera));
  5849. }
  5850. else if (size.width && size.height) {
  5851. width = size.width;
  5852. height = size.height;
  5853. }
  5854. else if (size.width && !size.height) {
  5855. width = size.width;
  5856. height = Math.round(width / engine.getAspectRatio(camera));
  5857. }
  5858. else if (size.height && !size.width) {
  5859. height = size.height;
  5860. width = Math.round(height * engine.getAspectRatio(camera));
  5861. }
  5862. else if (!isNaN(size)) {
  5863. height = size;
  5864. width = size;
  5865. }
  5866. else {
  5867. Tools.Error("Invalid 'size' parameter !");
  5868. return;
  5869. }
  5870. if (!screenshotCanvas) {
  5871. screenshotCanvas = document.createElement('canvas');
  5872. }
  5873. screenshotCanvas.width = width;
  5874. screenshotCanvas.height = height;
  5875. var renderContext = screenshotCanvas.getContext("2d");
  5876. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5877. var newWidth = width;
  5878. var newHeight = newWidth / ratio;
  5879. if (newHeight > height) {
  5880. newHeight = height;
  5881. newWidth = newHeight * ratio;
  5882. }
  5883. var offsetX = Math.max(0, width - newWidth) / 2;
  5884. var offsetY = Math.max(0, height - newHeight) / 2;
  5885. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5886. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5887. };
  5888. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5889. if (mimeType === void 0) { mimeType = "image/png"; }
  5890. if (samples === void 0) { samples = 1; }
  5891. var width;
  5892. var height;
  5893. //If a precision value is specified
  5894. if (size.precision) {
  5895. width = Math.round(engine.getRenderWidth() * size.precision);
  5896. height = Math.round(width / engine.getAspectRatio(camera));
  5897. size = { width: width, height: height };
  5898. }
  5899. else if (size.width && size.height) {
  5900. width = size.width;
  5901. height = size.height;
  5902. }
  5903. else if (size.width && !size.height) {
  5904. width = size.width;
  5905. height = Math.round(width / engine.getAspectRatio(camera));
  5906. size = { width: width, height: height };
  5907. }
  5908. else if (size.height && !size.width) {
  5909. height = size.height;
  5910. width = Math.round(height * engine.getAspectRatio(camera));
  5911. size = { width: width, height: height };
  5912. }
  5913. else if (!isNaN(size)) {
  5914. height = size;
  5915. width = size;
  5916. }
  5917. else {
  5918. Tools.Error("Invalid 'size' parameter !");
  5919. return;
  5920. }
  5921. var scene = camera.getScene();
  5922. var previousCamera = null;
  5923. if (scene.activeCamera !== camera) {
  5924. previousCamera = scene.activeCamera;
  5925. scene.activeCamera = camera;
  5926. }
  5927. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5928. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5929. texture.renderList = scene.meshes;
  5930. texture.samples = samples;
  5931. texture.onAfterRenderObservable.add(function () {
  5932. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5933. });
  5934. scene.incrementRenderId();
  5935. scene.resetCachedMaterial();
  5936. texture.render(true);
  5937. texture.dispose();
  5938. if (previousCamera) {
  5939. scene.activeCamera = previousCamera;
  5940. }
  5941. camera.getProjectionMatrix(true); // Force cache refresh;
  5942. };
  5943. // XHR response validator for local file scenario
  5944. Tools.ValidateXHRData = function (xhr, dataType) {
  5945. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5946. if (dataType === void 0) { dataType = 7; }
  5947. try {
  5948. if (dataType & 1) {
  5949. if (xhr.responseText && xhr.responseText.length > 0) {
  5950. return true;
  5951. }
  5952. else if (dataType === 1) {
  5953. return false;
  5954. }
  5955. }
  5956. if (dataType & 2) {
  5957. // Check header width and height since there is no "TGA" magic number
  5958. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5959. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5960. return true;
  5961. }
  5962. else if (dataType === 2) {
  5963. return false;
  5964. }
  5965. }
  5966. if (dataType & 4) {
  5967. // Check for the "DDS" magic number
  5968. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5969. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5970. return true;
  5971. }
  5972. else {
  5973. return false;
  5974. }
  5975. }
  5976. }
  5977. catch (e) {
  5978. // Global protection
  5979. }
  5980. return false;
  5981. };
  5982. /**
  5983. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5984. * Be aware Math.random() could cause collisions, but:
  5985. * "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"
  5986. */
  5987. Tools.RandomId = function () {
  5988. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5989. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5990. return v.toString(16);
  5991. });
  5992. };
  5993. Object.defineProperty(Tools, "NoneLogLevel", {
  5994. get: function () {
  5995. return Tools._NoneLogLevel;
  5996. },
  5997. enumerable: true,
  5998. configurable: true
  5999. });
  6000. Object.defineProperty(Tools, "MessageLogLevel", {
  6001. get: function () {
  6002. return Tools._MessageLogLevel;
  6003. },
  6004. enumerable: true,
  6005. configurable: true
  6006. });
  6007. Object.defineProperty(Tools, "WarningLogLevel", {
  6008. get: function () {
  6009. return Tools._WarningLogLevel;
  6010. },
  6011. enumerable: true,
  6012. configurable: true
  6013. });
  6014. Object.defineProperty(Tools, "ErrorLogLevel", {
  6015. get: function () {
  6016. return Tools._ErrorLogLevel;
  6017. },
  6018. enumerable: true,
  6019. configurable: true
  6020. });
  6021. Object.defineProperty(Tools, "AllLogLevel", {
  6022. get: function () {
  6023. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6024. },
  6025. enumerable: true,
  6026. configurable: true
  6027. });
  6028. Tools._AddLogEntry = function (entry) {
  6029. Tools._LogCache = entry + Tools._LogCache;
  6030. if (Tools.OnNewCacheEntry) {
  6031. Tools.OnNewCacheEntry(entry);
  6032. }
  6033. };
  6034. Tools._FormatMessage = function (message) {
  6035. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6036. var date = new Date();
  6037. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6038. };
  6039. Tools._LogDisabled = function (message) {
  6040. // nothing to do
  6041. };
  6042. Tools._LogEnabled = function (message) {
  6043. var formattedMessage = Tools._FormatMessage(message);
  6044. console.log("BJS - " + formattedMessage);
  6045. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6046. Tools._AddLogEntry(entry);
  6047. };
  6048. Tools._WarnDisabled = function (message) {
  6049. // nothing to do
  6050. };
  6051. Tools._WarnEnabled = function (message) {
  6052. var formattedMessage = Tools._FormatMessage(message);
  6053. console.warn("BJS - " + formattedMessage);
  6054. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6055. Tools._AddLogEntry(entry);
  6056. };
  6057. Tools._ErrorDisabled = function (message) {
  6058. // nothing to do
  6059. };
  6060. Tools._ErrorEnabled = function (message) {
  6061. Tools.errorsCount++;
  6062. var formattedMessage = Tools._FormatMessage(message);
  6063. console.error("BJS - " + formattedMessage);
  6064. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6065. Tools._AddLogEntry(entry);
  6066. };
  6067. Object.defineProperty(Tools, "LogCache", {
  6068. get: function () {
  6069. return Tools._LogCache;
  6070. },
  6071. enumerable: true,
  6072. configurable: true
  6073. });
  6074. Tools.ClearLogCache = function () {
  6075. Tools._LogCache = "";
  6076. Tools.errorsCount = 0;
  6077. };
  6078. Object.defineProperty(Tools, "LogLevels", {
  6079. set: function (level) {
  6080. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6081. Tools.Log = Tools._LogEnabled;
  6082. }
  6083. else {
  6084. Tools.Log = Tools._LogDisabled;
  6085. }
  6086. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6087. Tools.Warn = Tools._WarnEnabled;
  6088. }
  6089. else {
  6090. Tools.Warn = Tools._WarnDisabled;
  6091. }
  6092. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6093. Tools.Error = Tools._ErrorEnabled;
  6094. }
  6095. else {
  6096. Tools.Error = Tools._ErrorDisabled;
  6097. }
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6103. get: function () {
  6104. return Tools._PerformanceNoneLogLevel;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6110. get: function () {
  6111. return Tools._PerformanceUserMarkLogLevel;
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6117. get: function () {
  6118. return Tools._PerformanceConsoleLogLevel;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6124. set: function (level) {
  6125. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6126. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6127. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6128. return;
  6129. }
  6130. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6131. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6132. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6133. return;
  6134. }
  6135. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6136. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6142. };
  6143. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6144. };
  6145. Tools._StartUserMark = function (counterName, condition) {
  6146. if (condition === void 0) { condition = true; }
  6147. if (!condition || !Tools._performance.mark) {
  6148. return;
  6149. }
  6150. Tools._performance.mark(counterName + "-Begin");
  6151. };
  6152. Tools._EndUserMark = function (counterName, condition) {
  6153. if (condition === void 0) { condition = true; }
  6154. if (!condition || !Tools._performance.mark) {
  6155. return;
  6156. }
  6157. Tools._performance.mark(counterName + "-End");
  6158. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6159. };
  6160. Tools._StartPerformanceConsole = function (counterName, condition) {
  6161. if (condition === void 0) { condition = true; }
  6162. if (!condition) {
  6163. return;
  6164. }
  6165. Tools._StartUserMark(counterName, condition);
  6166. if (console.time) {
  6167. console.time(counterName);
  6168. }
  6169. };
  6170. Tools._EndPerformanceConsole = function (counterName, condition) {
  6171. if (condition === void 0) { condition = true; }
  6172. if (!condition) {
  6173. return;
  6174. }
  6175. Tools._EndUserMark(counterName, condition);
  6176. if (console.time) {
  6177. console.timeEnd(counterName);
  6178. }
  6179. };
  6180. Object.defineProperty(Tools, "Now", {
  6181. get: function () {
  6182. if (window.performance && window.performance.now) {
  6183. return window.performance.now();
  6184. }
  6185. return new Date().getTime();
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. /**
  6191. * This method will return the name of the class used to create the instance of the given object.
  6192. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6193. * @param object the object to get the class name from
  6194. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6195. */
  6196. Tools.getClassName = function (object, isType) {
  6197. if (isType === void 0) { isType = false; }
  6198. var name = null;
  6199. if (!isType && object.getClassName) {
  6200. name = object.getClassName();
  6201. }
  6202. else {
  6203. if (object instanceof Object) {
  6204. var classObj = isType ? object : Object.getPrototypeOf(object);
  6205. name = classObj.constructor["__bjsclassName__"];
  6206. }
  6207. if (!name) {
  6208. name = typeof object;
  6209. }
  6210. }
  6211. return name;
  6212. };
  6213. Tools.first = function (array, predicate) {
  6214. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6215. var el = array_1[_i];
  6216. if (predicate(el)) {
  6217. return el;
  6218. }
  6219. }
  6220. };
  6221. /**
  6222. * This method will return the name of the full name of the class, including its owning module (if any).
  6223. * 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).
  6224. * @param object the object to get the class name from
  6225. * @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.
  6226. */
  6227. Tools.getFullClassName = function (object, isType) {
  6228. if (isType === void 0) { isType = false; }
  6229. var className = null;
  6230. var moduleName = null;
  6231. if (!isType && object.getClassName) {
  6232. className = object.getClassName();
  6233. }
  6234. else {
  6235. if (object instanceof Object) {
  6236. var classObj = isType ? object : Object.getPrototypeOf(object);
  6237. className = classObj.constructor["__bjsclassName__"];
  6238. moduleName = classObj.constructor["__bjsmoduleName__"];
  6239. }
  6240. if (!className) {
  6241. className = typeof object;
  6242. }
  6243. }
  6244. if (!className) {
  6245. return null;
  6246. }
  6247. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6248. };
  6249. /**
  6250. * 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.
  6251. * @param array
  6252. */
  6253. Tools.arrayOrStringFeeder = function (array) {
  6254. return function (index) {
  6255. if (index >= array.length) {
  6256. return null;
  6257. }
  6258. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6259. if (val && val.getHashCode) {
  6260. val = val.getHashCode();
  6261. }
  6262. if (typeof val === "string") {
  6263. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6264. }
  6265. return val;
  6266. };
  6267. };
  6268. /**
  6269. * Compute the hashCode of a stream of number
  6270. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6271. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6272. * @return the hash code computed
  6273. */
  6274. Tools.hashCodeFromStream = function (feeder) {
  6275. // Based from here: http://stackoverflow.com/a/7616484/802124
  6276. var hash = 0;
  6277. var index = 0;
  6278. var chr = feeder(index++);
  6279. while (chr != null) {
  6280. hash = ((hash << 5) - hash) + chr;
  6281. hash |= 0; // Convert to 32bit integer
  6282. chr = feeder(index++);
  6283. }
  6284. return hash;
  6285. };
  6286. return Tools;
  6287. }());
  6288. Tools.BaseUrl = "";
  6289. Tools.CorsBehavior = "anonymous";
  6290. Tools.UseFallbackTexture = true;
  6291. // Used in case of a texture loading problem
  6292. 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";
  6293. // Logs
  6294. Tools._NoneLogLevel = 0;
  6295. Tools._MessageLogLevel = 1;
  6296. Tools._WarningLogLevel = 2;
  6297. Tools._ErrorLogLevel = 4;
  6298. Tools._LogCache = "";
  6299. Tools.errorsCount = 0;
  6300. Tools.Log = Tools._LogEnabled;
  6301. Tools.Warn = Tools._WarnEnabled;
  6302. Tools.Error = Tools._ErrorEnabled;
  6303. // Performances
  6304. Tools._PerformanceNoneLogLevel = 0;
  6305. Tools._PerformanceUserMarkLogLevel = 1;
  6306. Tools._PerformanceConsoleLogLevel = 2;
  6307. Tools._performance = window.performance;
  6308. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6309. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6310. BABYLON.Tools = Tools;
  6311. /**
  6312. * This class is used to track a performance counter which is number based.
  6313. * The user has access to many properties which give statistics of different nature
  6314. *
  6315. * The implementer can track two kinds of Performance Counter: time and count
  6316. * 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.
  6317. * 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.
  6318. */
  6319. var PerfCounter = (function () {
  6320. function PerfCounter() {
  6321. this._startMonitoringTime = 0;
  6322. this._min = 0;
  6323. this._max = 0;
  6324. this._average = 0;
  6325. this._lastSecAverage = 0;
  6326. this._current = 0;
  6327. this._totalValueCount = 0;
  6328. this._totalAccumulated = 0;
  6329. this._lastSecAccumulated = 0;
  6330. this._lastSecTime = 0;
  6331. this._lastSecValueCount = 0;
  6332. }
  6333. Object.defineProperty(PerfCounter.prototype, "min", {
  6334. /**
  6335. * Returns the smallest value ever
  6336. */
  6337. get: function () {
  6338. return this._min;
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(PerfCounter.prototype, "max", {
  6344. /**
  6345. * Returns the biggest value ever
  6346. */
  6347. get: function () {
  6348. return this._max;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(PerfCounter.prototype, "average", {
  6354. /**
  6355. * Returns the average value since the performance counter is running
  6356. */
  6357. get: function () {
  6358. return this._average;
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6364. /**
  6365. * Returns the average value of the last second the counter was monitored
  6366. */
  6367. get: function () {
  6368. return this._lastSecAverage;
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. Object.defineProperty(PerfCounter.prototype, "current", {
  6374. /**
  6375. * Returns the current value
  6376. */
  6377. get: function () {
  6378. return this._current;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(PerfCounter.prototype, "total", {
  6384. get: function () {
  6385. return this._totalAccumulated;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. /**
  6391. * Call this method to start monitoring a new frame.
  6392. * 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.
  6393. */
  6394. PerfCounter.prototype.fetchNewFrame = function () {
  6395. this._totalValueCount++;
  6396. this._current = 0;
  6397. this._lastSecValueCount++;
  6398. };
  6399. /**
  6400. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6401. * @param newCount the count value to add to the monitored count
  6402. * @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.
  6403. */
  6404. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6405. if (!PerfCounter.Enabled) {
  6406. return;
  6407. }
  6408. this._current += newCount;
  6409. if (fetchResult) {
  6410. this._fetchResult();
  6411. }
  6412. };
  6413. /**
  6414. * Start monitoring this performance counter
  6415. */
  6416. PerfCounter.prototype.beginMonitoring = function () {
  6417. if (!PerfCounter.Enabled) {
  6418. return;
  6419. }
  6420. this._startMonitoringTime = Tools.Now;
  6421. };
  6422. /**
  6423. * Compute the time lapsed since the previous beginMonitoring() call.
  6424. * @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
  6425. */
  6426. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6427. if (newFrame === void 0) { newFrame = true; }
  6428. if (!PerfCounter.Enabled) {
  6429. return;
  6430. }
  6431. if (newFrame) {
  6432. this.fetchNewFrame();
  6433. }
  6434. var currentTime = Tools.Now;
  6435. this._current = currentTime - this._startMonitoringTime;
  6436. if (newFrame) {
  6437. this._fetchResult();
  6438. }
  6439. };
  6440. PerfCounter.prototype._fetchResult = function () {
  6441. this._totalAccumulated += this._current;
  6442. this._lastSecAccumulated += this._current;
  6443. // Min/Max update
  6444. this._min = Math.min(this._min, this._current);
  6445. this._max = Math.max(this._max, this._current);
  6446. this._average = this._totalAccumulated / this._totalValueCount;
  6447. // Reset last sec?
  6448. var now = Tools.Now;
  6449. if ((now - this._lastSecTime) > 1000) {
  6450. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6451. this._lastSecTime = now;
  6452. this._lastSecAccumulated = 0;
  6453. this._lastSecValueCount = 0;
  6454. }
  6455. };
  6456. return PerfCounter;
  6457. }());
  6458. PerfCounter.Enabled = true;
  6459. BABYLON.PerfCounter = PerfCounter;
  6460. /**
  6461. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6462. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6463. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6464. * @param name The name of the class, case should be preserved
  6465. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6466. */
  6467. function className(name, module) {
  6468. return function (target) {
  6469. target["__bjsclassName__"] = name;
  6470. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6471. };
  6472. }
  6473. BABYLON.className = className;
  6474. /**
  6475. * An implementation of a loop for asynchronous functions.
  6476. */
  6477. var AsyncLoop = (function () {
  6478. /**
  6479. * Constroctor.
  6480. * @param iterations the number of iterations.
  6481. * @param _fn the function to run each iteration
  6482. * @param _successCallback the callback that will be called upon succesful execution
  6483. * @param offset starting offset.
  6484. */
  6485. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6486. if (offset === void 0) { offset = 0; }
  6487. this.iterations = iterations;
  6488. this._fn = _fn;
  6489. this._successCallback = _successCallback;
  6490. this.index = offset - 1;
  6491. this._done = false;
  6492. }
  6493. /**
  6494. * Execute the next iteration. Must be called after the last iteration was finished.
  6495. */
  6496. AsyncLoop.prototype.executeNext = function () {
  6497. if (!this._done) {
  6498. if (this.index + 1 < this.iterations) {
  6499. ++this.index;
  6500. this._fn(this);
  6501. }
  6502. else {
  6503. this.breakLoop();
  6504. }
  6505. }
  6506. };
  6507. /**
  6508. * Break the loop and run the success callback.
  6509. */
  6510. AsyncLoop.prototype.breakLoop = function () {
  6511. this._done = true;
  6512. this._successCallback();
  6513. };
  6514. /**
  6515. * Helper function
  6516. */
  6517. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6518. if (offset === void 0) { offset = 0; }
  6519. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6520. loop.executeNext();
  6521. return loop;
  6522. };
  6523. /**
  6524. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6525. * @param iterations total number of iterations
  6526. * @param syncedIterations number of synchronous iterations in each async iteration.
  6527. * @param fn the function to call each iteration.
  6528. * @param callback a success call back that will be called when iterating stops.
  6529. * @param breakFunction a break condition (optional)
  6530. * @param timeout timeout settings for the setTimeout function. default - 0.
  6531. * @constructor
  6532. */
  6533. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6534. if (timeout === void 0) { timeout = 0; }
  6535. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6536. if (breakFunction && breakFunction())
  6537. loop.breakLoop();
  6538. else {
  6539. setTimeout(function () {
  6540. for (var i = 0; i < syncedIterations; ++i) {
  6541. var iteration = (loop.index * syncedIterations) + i;
  6542. if (iteration >= iterations)
  6543. break;
  6544. fn(iteration);
  6545. if (breakFunction && breakFunction()) {
  6546. loop.breakLoop();
  6547. break;
  6548. }
  6549. }
  6550. loop.executeNext();
  6551. }, timeout);
  6552. }
  6553. }, callback);
  6554. };
  6555. return AsyncLoop;
  6556. }());
  6557. BABYLON.AsyncLoop = AsyncLoop;
  6558. })(BABYLON || (BABYLON = {}));
  6559. //# sourceMappingURL=babylon.tools.js.map
  6560. var BABYLON;
  6561. (function (BABYLON) {
  6562. var Internals;
  6563. (function (Internals) {
  6564. var _AlphaState = (function () {
  6565. /**
  6566. * Initializes the state.
  6567. */
  6568. function _AlphaState() {
  6569. this._isAlphaBlendDirty = false;
  6570. this._isBlendFunctionParametersDirty = false;
  6571. this._isBlendEquationParametersDirty = false;
  6572. this._isBlendConstantsDirty = false;
  6573. this._alphaBlend = false;
  6574. this._blendFunctionParameters = new Array(4);
  6575. this._blendEquationParameters = new Array(2);
  6576. this._blendConstants = new Array(4);
  6577. this.reset();
  6578. }
  6579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6580. get: function () {
  6581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6587. get: function () {
  6588. return this._alphaBlend;
  6589. },
  6590. set: function (value) {
  6591. if (this._alphaBlend === value) {
  6592. return;
  6593. }
  6594. this._alphaBlend = value;
  6595. this._isAlphaBlendDirty = true;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6601. if (this._blendConstants[0] === r &&
  6602. this._blendConstants[1] === g &&
  6603. this._blendConstants[2] === b &&
  6604. this._blendConstants[3] === a) {
  6605. return;
  6606. }
  6607. this._blendConstants[0] = r;
  6608. this._blendConstants[1] = g;
  6609. this._blendConstants[2] = b;
  6610. this._blendConstants[3] = a;
  6611. this._isBlendConstantsDirty = true;
  6612. };
  6613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6614. if (this._blendFunctionParameters[0] === value0 &&
  6615. this._blendFunctionParameters[1] === value1 &&
  6616. this._blendFunctionParameters[2] === value2 &&
  6617. this._blendFunctionParameters[3] === value3) {
  6618. return;
  6619. }
  6620. this._blendFunctionParameters[0] = value0;
  6621. this._blendFunctionParameters[1] = value1;
  6622. this._blendFunctionParameters[2] = value2;
  6623. this._blendFunctionParameters[3] = value3;
  6624. this._isBlendFunctionParametersDirty = true;
  6625. };
  6626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6627. if (this._blendEquationParameters[0] === rgb &&
  6628. this._blendEquationParameters[1] === alpha) {
  6629. return;
  6630. }
  6631. this._blendEquationParameters[0] = rgb;
  6632. this._blendEquationParameters[1] = alpha;
  6633. this._isBlendEquationParametersDirty = true;
  6634. };
  6635. _AlphaState.prototype.reset = function () {
  6636. this._alphaBlend = false;
  6637. this._blendFunctionParameters[0] = null;
  6638. this._blendFunctionParameters[1] = null;
  6639. this._blendFunctionParameters[2] = null;
  6640. this._blendFunctionParameters[3] = null;
  6641. this._blendEquationParameters[0] = null;
  6642. this._blendEquationParameters[1] = null;
  6643. this._blendConstants[0] = null;
  6644. this._blendConstants[1] = null;
  6645. this._blendConstants[2] = null;
  6646. this._blendConstants[3] = null;
  6647. this._isAlphaBlendDirty = true;
  6648. this._isBlendFunctionParametersDirty = false;
  6649. this._isBlendEquationParametersDirty = false;
  6650. this._isBlendConstantsDirty = false;
  6651. };
  6652. _AlphaState.prototype.apply = function (gl) {
  6653. if (!this.isDirty) {
  6654. return;
  6655. }
  6656. // Alpha blend
  6657. if (this._isAlphaBlendDirty) {
  6658. if (this._alphaBlend) {
  6659. gl.enable(gl.BLEND);
  6660. }
  6661. else {
  6662. gl.disable(gl.BLEND);
  6663. }
  6664. this._isAlphaBlendDirty = false;
  6665. }
  6666. // Alpha function
  6667. if (this._isBlendFunctionParametersDirty) {
  6668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6669. this._isBlendFunctionParametersDirty = false;
  6670. }
  6671. // Alpha equation
  6672. if (this._isBlendEquationParametersDirty) {
  6673. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6674. this._isBlendEquationParametersDirty = false;
  6675. }
  6676. // Constants
  6677. if (this._isBlendConstantsDirty) {
  6678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6679. this._isBlendConstantsDirty = false;
  6680. }
  6681. };
  6682. return _AlphaState;
  6683. }());
  6684. Internals._AlphaState = _AlphaState;
  6685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6686. })(BABYLON || (BABYLON = {}));
  6687. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6688. var BABYLON;
  6689. (function (BABYLON) {
  6690. var Internals;
  6691. (function (Internals) {
  6692. var _DepthCullingState = (function () {
  6693. /**
  6694. * Initializes the state.
  6695. */
  6696. function _DepthCullingState() {
  6697. this._isDepthTestDirty = false;
  6698. this._isDepthMaskDirty = false;
  6699. this._isDepthFuncDirty = false;
  6700. this._isCullFaceDirty = false;
  6701. this._isCullDirty = false;
  6702. this._isZOffsetDirty = false;
  6703. this.reset();
  6704. }
  6705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6706. get: function () {
  6707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6713. get: function () {
  6714. return this._zOffset;
  6715. },
  6716. set: function (value) {
  6717. if (this._zOffset === value) {
  6718. return;
  6719. }
  6720. this._zOffset = value;
  6721. this._isZOffsetDirty = true;
  6722. },
  6723. enumerable: true,
  6724. configurable: true
  6725. });
  6726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6727. get: function () {
  6728. return this._cullFace;
  6729. },
  6730. set: function (value) {
  6731. if (this._cullFace === value) {
  6732. return;
  6733. }
  6734. this._cullFace = value;
  6735. this._isCullFaceDirty = true;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6741. get: function () {
  6742. return this._cull;
  6743. },
  6744. set: function (value) {
  6745. if (this._cull === value) {
  6746. return;
  6747. }
  6748. this._cull = value;
  6749. this._isCullDirty = true;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6755. get: function () {
  6756. return this._depthFunc;
  6757. },
  6758. set: function (value) {
  6759. if (this._depthFunc === value) {
  6760. return;
  6761. }
  6762. this._depthFunc = value;
  6763. this._isDepthFuncDirty = true;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6769. get: function () {
  6770. return this._depthMask;
  6771. },
  6772. set: function (value) {
  6773. if (this._depthMask === value) {
  6774. return;
  6775. }
  6776. this._depthMask = value;
  6777. this._isDepthMaskDirty = true;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6783. get: function () {
  6784. return this._depthTest;
  6785. },
  6786. set: function (value) {
  6787. if (this._depthTest === value) {
  6788. return;
  6789. }
  6790. this._depthTest = value;
  6791. this._isDepthTestDirty = true;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. _DepthCullingState.prototype.reset = function () {
  6797. this._depthMask = true;
  6798. this._depthTest = true;
  6799. this._depthFunc = null;
  6800. this._cullFace = null;
  6801. this._cull = null;
  6802. this._zOffset = 0;
  6803. this._isDepthTestDirty = true;
  6804. this._isDepthMaskDirty = true;
  6805. this._isDepthFuncDirty = false;
  6806. this._isCullFaceDirty = false;
  6807. this._isCullDirty = false;
  6808. this._isZOffsetDirty = false;
  6809. };
  6810. _DepthCullingState.prototype.apply = function (gl) {
  6811. if (!this.isDirty) {
  6812. return;
  6813. }
  6814. // Cull
  6815. if (this._isCullDirty) {
  6816. if (this.cull) {
  6817. gl.enable(gl.CULL_FACE);
  6818. }
  6819. else {
  6820. gl.disable(gl.CULL_FACE);
  6821. }
  6822. this._isCullDirty = false;
  6823. }
  6824. // Cull face
  6825. if (this._isCullFaceDirty) {
  6826. gl.cullFace(this.cullFace);
  6827. this._isCullFaceDirty = false;
  6828. }
  6829. // Depth mask
  6830. if (this._isDepthMaskDirty) {
  6831. gl.depthMask(this.depthMask);
  6832. this._isDepthMaskDirty = false;
  6833. }
  6834. // Depth test
  6835. if (this._isDepthTestDirty) {
  6836. if (this.depthTest) {
  6837. gl.enable(gl.DEPTH_TEST);
  6838. }
  6839. else {
  6840. gl.disable(gl.DEPTH_TEST);
  6841. }
  6842. this._isDepthTestDirty = false;
  6843. }
  6844. // Depth func
  6845. if (this._isDepthFuncDirty) {
  6846. gl.depthFunc(this.depthFunc);
  6847. this._isDepthFuncDirty = false;
  6848. }
  6849. // zOffset
  6850. if (this._isZOffsetDirty) {
  6851. if (this.zOffset) {
  6852. gl.enable(gl.POLYGON_OFFSET_FILL);
  6853. gl.polygonOffset(this.zOffset, 0);
  6854. }
  6855. else {
  6856. gl.disable(gl.POLYGON_OFFSET_FILL);
  6857. }
  6858. this._isZOffsetDirty = false;
  6859. }
  6860. };
  6861. return _DepthCullingState;
  6862. }());
  6863. Internals._DepthCullingState = _DepthCullingState;
  6864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6865. })(BABYLON || (BABYLON = {}));
  6866. //# sourceMappingURL=babylon.depthCullingState.js.map
  6867. var BABYLON;
  6868. (function (BABYLON) {
  6869. var Internals;
  6870. (function (Internals) {
  6871. var _StencilState = (function () {
  6872. function _StencilState() {
  6873. this._isStencilTestDirty = false;
  6874. this._isStencilMaskDirty = false;
  6875. this._isStencilFuncDirty = false;
  6876. this._isStencilOpDirty = false;
  6877. this.reset();
  6878. }
  6879. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6880. get: function () {
  6881. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6887. get: function () {
  6888. return this._stencilFunc;
  6889. },
  6890. set: function (value) {
  6891. if (this._stencilFunc === value) {
  6892. return;
  6893. }
  6894. this._stencilFunc = value;
  6895. this._isStencilFuncDirty = true;
  6896. },
  6897. enumerable: true,
  6898. configurable: true
  6899. });
  6900. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6901. get: function () {
  6902. return this._stencilFuncRef;
  6903. },
  6904. set: function (value) {
  6905. if (this._stencilFuncRef === value) {
  6906. return;
  6907. }
  6908. this._stencilFuncRef = value;
  6909. this._isStencilFuncDirty = true;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6915. get: function () {
  6916. return this._stencilFuncMask;
  6917. },
  6918. set: function (value) {
  6919. if (this._stencilFuncMask === value) {
  6920. return;
  6921. }
  6922. this._stencilFuncMask = value;
  6923. this._isStencilFuncDirty = true;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6929. get: function () {
  6930. return this._stencilOpStencilFail;
  6931. },
  6932. set: function (value) {
  6933. if (this._stencilOpStencilFail === value) {
  6934. return;
  6935. }
  6936. this._stencilOpStencilFail = value;
  6937. this._isStencilOpDirty = true;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6943. get: function () {
  6944. return this._stencilOpDepthFail;
  6945. },
  6946. set: function (value) {
  6947. if (this._stencilOpDepthFail === value) {
  6948. return;
  6949. }
  6950. this._stencilOpDepthFail = value;
  6951. this._isStencilOpDirty = true;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6957. get: function () {
  6958. return this._stencilOpStencilDepthPass;
  6959. },
  6960. set: function (value) {
  6961. if (this._stencilOpStencilDepthPass === value) {
  6962. return;
  6963. }
  6964. this._stencilOpStencilDepthPass = value;
  6965. this._isStencilOpDirty = true;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6971. get: function () {
  6972. return this._stencilMask;
  6973. },
  6974. set: function (value) {
  6975. if (this._stencilMask === value) {
  6976. return;
  6977. }
  6978. this._stencilMask = value;
  6979. this._isStencilMaskDirty = true;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6985. get: function () {
  6986. return this._stencilTest;
  6987. },
  6988. set: function (value) {
  6989. if (this._stencilTest === value) {
  6990. return;
  6991. }
  6992. this._stencilTest = value;
  6993. this._isStencilTestDirty = true;
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. _StencilState.prototype.reset = function () {
  6999. this._stencilTest = false;
  7000. this._stencilMask = 0xFF;
  7001. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7002. this._stencilFuncRef = 1;
  7003. this._stencilFuncMask = 0xFF;
  7004. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7005. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7006. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7007. this._isStencilTestDirty = true;
  7008. this._isStencilMaskDirty = true;
  7009. this._isStencilFuncDirty = true;
  7010. this._isStencilOpDirty = true;
  7011. };
  7012. _StencilState.prototype.apply = function (gl) {
  7013. if (!this.isDirty) {
  7014. return;
  7015. }
  7016. // Stencil test
  7017. if (this._isStencilTestDirty) {
  7018. if (this.stencilTest) {
  7019. gl.enable(gl.STENCIL_TEST);
  7020. }
  7021. else {
  7022. gl.disable(gl.STENCIL_TEST);
  7023. }
  7024. this._isStencilTestDirty = false;
  7025. }
  7026. // Stencil mask
  7027. if (this._isStencilMaskDirty) {
  7028. gl.stencilMask(this.stencilMask);
  7029. this._isStencilMaskDirty = false;
  7030. }
  7031. // Stencil func
  7032. if (this._isStencilFuncDirty) {
  7033. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7034. this._isStencilFuncDirty = false;
  7035. }
  7036. // Stencil op
  7037. if (this._isStencilOpDirty) {
  7038. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7039. this._isStencilOpDirty = false;
  7040. }
  7041. };
  7042. return _StencilState;
  7043. }());
  7044. Internals._StencilState = _StencilState;
  7045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7046. })(BABYLON || (BABYLON = {}));
  7047. //# sourceMappingURL=babylon.stencilState.js.map
  7048. var BABYLON;
  7049. (function (BABYLON) {
  7050. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7051. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7052. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7053. gl.compileShader(shader);
  7054. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7055. throw new Error(gl.getShaderInfoLog(shader));
  7056. }
  7057. return shader;
  7058. };
  7059. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7060. var magFilter = gl.NEAREST;
  7061. var minFilter = gl.NEAREST;
  7062. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7063. magFilter = gl.LINEAR;
  7064. if (generateMipMaps) {
  7065. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7066. }
  7067. else {
  7068. minFilter = gl.LINEAR;
  7069. }
  7070. }
  7071. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7072. magFilter = gl.LINEAR;
  7073. if (generateMipMaps) {
  7074. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7075. }
  7076. else {
  7077. minFilter = gl.LINEAR;
  7078. }
  7079. }
  7080. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7081. magFilter = gl.NEAREST;
  7082. if (generateMipMaps) {
  7083. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7084. }
  7085. else {
  7086. minFilter = gl.NEAREST;
  7087. }
  7088. }
  7089. return {
  7090. min: minFilter,
  7091. mag: magFilter
  7092. };
  7093. };
  7094. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7096. var engine = scene.getEngine();
  7097. if (!engine) {
  7098. return;
  7099. }
  7100. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7101. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7102. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7104. texture._baseWidth = width;
  7105. texture._baseHeight = height;
  7106. texture._width = potWidth;
  7107. texture._height = potHeight;
  7108. texture.isReady = true;
  7109. processFunction(potWidth, potHeight);
  7110. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7113. if (!noMipmap && !isCompressed) {
  7114. gl.generateMipmap(gl.TEXTURE_2D);
  7115. }
  7116. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7117. engine.resetTextureCache();
  7118. scene._removePendingData(texture);
  7119. texture.onLoadedCallbacks.forEach(function (callback) {
  7120. callback();
  7121. });
  7122. texture.onLoadedCallbacks = [];
  7123. };
  7124. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7125. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7126. var img;
  7127. var onload = function () {
  7128. loadedImages[index] = img;
  7129. loadedImages._internalCount++;
  7130. scene._removePendingData(img);
  7131. if (loadedImages._internalCount === 6) {
  7132. onfinish(loadedImages);
  7133. }
  7134. };
  7135. var onerror = function () {
  7136. scene._removePendingData(img);
  7137. if (onErrorCallBack) {
  7138. onErrorCallBack();
  7139. }
  7140. };
  7141. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7142. scene._addPendingData(img);
  7143. };
  7144. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7145. if (onError === void 0) { onError = null; }
  7146. var loadedImages = [];
  7147. loadedImages._internalCount = 0;
  7148. for (var index = 0; index < 6; index++) {
  7149. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7150. }
  7151. };
  7152. var InstancingAttributeInfo = (function () {
  7153. function InstancingAttributeInfo() {
  7154. }
  7155. return InstancingAttributeInfo;
  7156. }());
  7157. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7158. var EngineCapabilities = (function () {
  7159. function EngineCapabilities() {
  7160. }
  7161. return EngineCapabilities;
  7162. }());
  7163. BABYLON.EngineCapabilities = EngineCapabilities;
  7164. /**
  7165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7166. */
  7167. var Engine = (function () {
  7168. /**
  7169. * @constructor
  7170. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7171. * @param {boolean} [antialias] - enable antialias
  7172. * @param options - further options to be sent to the getContext function
  7173. */
  7174. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7175. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7176. var _this = this;
  7177. // Public members
  7178. this.isFullscreen = false;
  7179. this.isPointerLock = false;
  7180. this.cullBackFaces = true;
  7181. this.renderEvenInBackground = true;
  7182. this.preventCacheWipeBetweenFrames = false;
  7183. // To enable/disable IDB support and avoid XHR on .manifest
  7184. this.enableOfflineSupport = BABYLON.Database;
  7185. this.scenes = new Array();
  7186. // Observables
  7187. /**
  7188. * Observable event triggered each time the rendering canvas is resized
  7189. */
  7190. this.onResizeObservable = new BABYLON.Observable();
  7191. /**
  7192. * Observable event triggered each time the canvas lost focus
  7193. */
  7194. this.onCanvasBlurObservable = new BABYLON.Observable();
  7195. this._windowIsBackground = false;
  7196. this._webGLVersion = 1.0;
  7197. this._badOS = false;
  7198. this._drawCalls = new BABYLON.PerfCounter();
  7199. this._renderingQueueLaunched = false;
  7200. this._activeRenderLoops = [];
  7201. // FPS
  7202. this.fpsRange = 60;
  7203. this.previousFramesDuration = [];
  7204. this.fps = 60;
  7205. this.deltaTime = 0;
  7206. // States
  7207. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7208. this._stencilState = new BABYLON.Internals._StencilState();
  7209. this._alphaState = new BABYLON.Internals._AlphaState();
  7210. this._alphaMode = Engine.ALPHA_DISABLE;
  7211. // Cache
  7212. this._loadedTexturesCache = new Array();
  7213. this._maxTextureChannels = 16;
  7214. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7215. this._compiledEffects = {};
  7216. this._vertexAttribArraysEnabled = [];
  7217. this._uintIndicesCurrentlySet = false;
  7218. this._currentBoundBuffer = new Array();
  7219. this._currentBufferPointers = [];
  7220. this._currentInstanceLocations = new Array();
  7221. this._currentInstanceBuffers = new Array();
  7222. this._vaoRecordInProgress = false;
  7223. this._mustWipeVertexAttributes = false;
  7224. // Hardware supported Compressed Textures
  7225. this._texturesSupported = new Array();
  7226. this._onVRFullScreenTriggered = function () {
  7227. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7228. //get the old size before we change
  7229. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7230. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7231. //get the width and height, change the render size
  7232. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7233. var width, height;
  7234. _this.setHardwareScalingLevel(1);
  7235. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7236. }
  7237. else {
  7238. //When the specs are implemented, need to uncomment this.
  7239. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7240. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7241. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7242. _this._vrDisplayEnabled = undefined;
  7243. }
  7244. };
  7245. this._renderingCanvas = canvas;
  7246. Engine.Instances.push(this);
  7247. options = options || {};
  7248. if (antialias != null) {
  7249. options.antialias = antialias;
  7250. }
  7251. if (options.preserveDrawingBuffer === undefined) {
  7252. options.preserveDrawingBuffer = false;
  7253. }
  7254. if (options.audioEngine === undefined) {
  7255. options.audioEngine = true;
  7256. }
  7257. if (options.stencil === undefined) {
  7258. options.stencil = true;
  7259. }
  7260. // GL
  7261. if (!options.disableWebGL2Support) {
  7262. try {
  7263. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7264. if (this._gl) {
  7265. this._webGLVersion = 2.0;
  7266. }
  7267. }
  7268. catch (e) {
  7269. // Do nothing
  7270. }
  7271. }
  7272. if (!this._gl) {
  7273. if (!canvas) {
  7274. throw new Error("The provided canvas is null or undefined.");
  7275. }
  7276. try {
  7277. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7278. }
  7279. catch (e) {
  7280. throw new Error("WebGL not supported");
  7281. }
  7282. }
  7283. if (!this._gl) {
  7284. throw new Error("WebGL not supported");
  7285. }
  7286. this._onBlur = function () {
  7287. _this._windowIsBackground = true;
  7288. };
  7289. this._onFocus = function () {
  7290. _this._windowIsBackground = false;
  7291. };
  7292. this._onCanvasBlur = function () {
  7293. _this.onCanvasBlurObservable.notifyObservers(_this);
  7294. };
  7295. window.addEventListener("blur", this._onBlur);
  7296. window.addEventListener("focus", this._onFocus);
  7297. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7298. // Viewport
  7299. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7300. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7301. this.resize();
  7302. // Caps
  7303. this._isStencilEnable = options.stencil;
  7304. this._caps = new EngineCapabilities();
  7305. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7306. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7307. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7308. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7309. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7310. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7311. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7312. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7313. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7314. // Infos
  7315. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7316. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7317. if (rendererInfo != null) {
  7318. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7319. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7320. }
  7321. if (!this._glVendor) {
  7322. this._glVendor = "Unknown vendor";
  7323. }
  7324. if (!this._glRenderer) {
  7325. this._glRenderer = "Unknown renderer";
  7326. }
  7327. // Constants
  7328. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7329. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7330. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7331. // Extensions
  7332. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7333. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7334. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7335. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7336. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7337. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7338. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7339. 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');
  7340. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7341. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7342. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7343. this._caps.highPrecisionShaderSupported = true;
  7344. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7345. // Checks if some of the format renders first to allow the use of webgl inspector.
  7346. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7347. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7348. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7349. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7350. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7351. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7352. if (this._webGLVersion > 1) {
  7353. this._gl.HALF_FLOAT_OES = 0x140B;
  7354. }
  7355. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7356. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7357. // Vertex array object
  7358. if (this._webGLVersion > 1) {
  7359. this._caps.vertexArrayObject = true;
  7360. }
  7361. else {
  7362. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7363. if (vertexArrayObjectExtension != null) {
  7364. this._caps.vertexArrayObject = true;
  7365. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7366. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7367. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7368. }
  7369. else {
  7370. this._caps.vertexArrayObject = false;
  7371. }
  7372. }
  7373. // Instances count
  7374. if (this._webGLVersion > 1) {
  7375. this._caps.instancedArrays = true;
  7376. }
  7377. else {
  7378. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7379. if (instanceExtension != null) {
  7380. this._caps.instancedArrays = true;
  7381. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7382. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7383. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7384. }
  7385. else {
  7386. this._caps.instancedArrays = false;
  7387. }
  7388. }
  7389. // Intelligently add supported compressed formats in order to check for.
  7390. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7391. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7392. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7393. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7394. if (this._caps.astc)
  7395. this.texturesSupported.push('-astc.ktx');
  7396. if (this._caps.s3tc)
  7397. this.texturesSupported.push('-dxt.ktx');
  7398. if (this._caps.pvrtc)
  7399. this.texturesSupported.push('-pvrtc.ktx');
  7400. if (this._caps.etc2)
  7401. this.texturesSupported.push('-etc2.ktx');
  7402. if (this._caps.etc1)
  7403. this.texturesSupported.push('-etc1.ktx');
  7404. if (this._gl.getShaderPrecisionFormat) {
  7405. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7406. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7407. }
  7408. // Depth buffer
  7409. this.setDepthBuffer(true);
  7410. this.setDepthFunctionToLessOrEqual();
  7411. this.setDepthWrite(true);
  7412. // Fullscreen
  7413. this._onFullscreenChange = function () {
  7414. if (document.fullscreen !== undefined) {
  7415. _this.isFullscreen = document.fullscreen;
  7416. }
  7417. else if (document.mozFullScreen !== undefined) {
  7418. _this.isFullscreen = document.mozFullScreen;
  7419. }
  7420. else if (document.webkitIsFullScreen !== undefined) {
  7421. _this.isFullscreen = document.webkitIsFullScreen;
  7422. }
  7423. else if (document.msIsFullScreen !== undefined) {
  7424. _this.isFullscreen = document.msIsFullScreen;
  7425. }
  7426. // Pointer lock
  7427. if (_this.isFullscreen && _this._pointerLockRequested) {
  7428. canvas.requestPointerLock = canvas.requestPointerLock ||
  7429. canvas.msRequestPointerLock ||
  7430. canvas.mozRequestPointerLock ||
  7431. canvas.webkitRequestPointerLock;
  7432. if (canvas.requestPointerLock) {
  7433. canvas.requestPointerLock();
  7434. }
  7435. }
  7436. };
  7437. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7438. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7439. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7440. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7441. // Pointer lock
  7442. this._onPointerLockChange = function () {
  7443. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7444. document.webkitPointerLockElement === canvas ||
  7445. document.msPointerLockElement === canvas ||
  7446. document.pointerLockElement === canvas);
  7447. };
  7448. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7449. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7450. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7451. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7452. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7453. Engine.audioEngine = new BABYLON.AudioEngine();
  7454. }
  7455. //Load WebVR Devices
  7456. if (options.autoEnableWebVR) {
  7457. this.initWebVR();
  7458. }
  7459. //Detect if we are running on a faulty buggy OS.
  7460. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7461. //ua sniffing is the tool of the devil.
  7462. this._badOS = regexp.test(navigator.userAgent);
  7463. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7464. }
  7465. Object.defineProperty(Engine, "LastCreatedEngine", {
  7466. get: function () {
  7467. if (Engine.Instances.length === 0) {
  7468. return null;
  7469. }
  7470. return Engine.Instances[Engine.Instances.length - 1];
  7471. },
  7472. enumerable: true,
  7473. configurable: true
  7474. });
  7475. Object.defineProperty(Engine, "LastCreatedScene", {
  7476. get: function () {
  7477. var lastCreatedEngine = Engine.LastCreatedEngine;
  7478. if (!lastCreatedEngine) {
  7479. return null;
  7480. }
  7481. if (lastCreatedEngine.scenes.length === 0) {
  7482. return null;
  7483. }
  7484. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7485. },
  7486. enumerable: true,
  7487. configurable: true
  7488. });
  7489. /**
  7490. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7491. */
  7492. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7493. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7494. var engine = Engine.Instances[engineIndex];
  7495. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7496. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7497. }
  7498. }
  7499. };
  7500. Object.defineProperty(Engine, "NEVER", {
  7501. get: function () {
  7502. return Engine._NEVER;
  7503. },
  7504. enumerable: true,
  7505. configurable: true
  7506. });
  7507. Object.defineProperty(Engine, "ALWAYS", {
  7508. get: function () {
  7509. return Engine._ALWAYS;
  7510. },
  7511. enumerable: true,
  7512. configurable: true
  7513. });
  7514. Object.defineProperty(Engine, "LESS", {
  7515. get: function () {
  7516. return Engine._LESS;
  7517. },
  7518. enumerable: true,
  7519. configurable: true
  7520. });
  7521. Object.defineProperty(Engine, "EQUAL", {
  7522. get: function () {
  7523. return Engine._EQUAL;
  7524. },
  7525. enumerable: true,
  7526. configurable: true
  7527. });
  7528. Object.defineProperty(Engine, "LEQUAL", {
  7529. get: function () {
  7530. return Engine._LEQUAL;
  7531. },
  7532. enumerable: true,
  7533. configurable: true
  7534. });
  7535. Object.defineProperty(Engine, "GREATER", {
  7536. get: function () {
  7537. return Engine._GREATER;
  7538. },
  7539. enumerable: true,
  7540. configurable: true
  7541. });
  7542. Object.defineProperty(Engine, "GEQUAL", {
  7543. get: function () {
  7544. return Engine._GEQUAL;
  7545. },
  7546. enumerable: true,
  7547. configurable: true
  7548. });
  7549. Object.defineProperty(Engine, "NOTEQUAL", {
  7550. get: function () {
  7551. return Engine._NOTEQUAL;
  7552. },
  7553. enumerable: true,
  7554. configurable: true
  7555. });
  7556. Object.defineProperty(Engine, "KEEP", {
  7557. get: function () {
  7558. return Engine._KEEP;
  7559. },
  7560. enumerable: true,
  7561. configurable: true
  7562. });
  7563. Object.defineProperty(Engine, "REPLACE", {
  7564. get: function () {
  7565. return Engine._REPLACE;
  7566. },
  7567. enumerable: true,
  7568. configurable: true
  7569. });
  7570. Object.defineProperty(Engine, "INCR", {
  7571. get: function () {
  7572. return Engine._INCR;
  7573. },
  7574. enumerable: true,
  7575. configurable: true
  7576. });
  7577. Object.defineProperty(Engine, "DECR", {
  7578. get: function () {
  7579. return Engine._DECR;
  7580. },
  7581. enumerable: true,
  7582. configurable: true
  7583. });
  7584. Object.defineProperty(Engine, "INVERT", {
  7585. get: function () {
  7586. return Engine._INVERT;
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. Object.defineProperty(Engine, "INCR_WRAP", {
  7592. get: function () {
  7593. return Engine._INCR_WRAP;
  7594. },
  7595. enumerable: true,
  7596. configurable: true
  7597. });
  7598. Object.defineProperty(Engine, "DECR_WRAP", {
  7599. get: function () {
  7600. return Engine._DECR_WRAP;
  7601. },
  7602. enumerable: true,
  7603. configurable: true
  7604. });
  7605. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7606. get: function () {
  7607. return Engine._ALPHA_DISABLE;
  7608. },
  7609. enumerable: true,
  7610. configurable: true
  7611. });
  7612. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7613. get: function () {
  7614. return Engine._ALPHA_ONEONE;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(Engine, "ALPHA_ADD", {
  7620. get: function () {
  7621. return Engine._ALPHA_ADD;
  7622. },
  7623. enumerable: true,
  7624. configurable: true
  7625. });
  7626. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7627. get: function () {
  7628. return Engine._ALPHA_COMBINE;
  7629. },
  7630. enumerable: true,
  7631. configurable: true
  7632. });
  7633. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7634. get: function () {
  7635. return Engine._ALPHA_SUBTRACT;
  7636. },
  7637. enumerable: true,
  7638. configurable: true
  7639. });
  7640. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7641. get: function () {
  7642. return Engine._ALPHA_MULTIPLY;
  7643. },
  7644. enumerable: true,
  7645. configurable: true
  7646. });
  7647. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7648. get: function () {
  7649. return Engine._ALPHA_MAXIMIZED;
  7650. },
  7651. enumerable: true,
  7652. configurable: true
  7653. });
  7654. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7655. get: function () {
  7656. return Engine._ALPHA_PREMULTIPLIED;
  7657. },
  7658. enumerable: true,
  7659. configurable: true
  7660. });
  7661. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7662. get: function () {
  7663. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7664. },
  7665. enumerable: true,
  7666. configurable: true
  7667. });
  7668. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7669. get: function () {
  7670. return Engine._ALPHA_INTERPOLATE;
  7671. },
  7672. enumerable: true,
  7673. configurable: true
  7674. });
  7675. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7676. get: function () {
  7677. return Engine._ALPHA_SCREENMODE;
  7678. },
  7679. enumerable: true,
  7680. configurable: true
  7681. });
  7682. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7683. get: function () {
  7684. return Engine._DELAYLOADSTATE_NONE;
  7685. },
  7686. enumerable: true,
  7687. configurable: true
  7688. });
  7689. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7690. get: function () {
  7691. return Engine._DELAYLOADSTATE_LOADED;
  7692. },
  7693. enumerable: true,
  7694. configurable: true
  7695. });
  7696. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7697. get: function () {
  7698. return Engine._DELAYLOADSTATE_LOADING;
  7699. },
  7700. enumerable: true,
  7701. configurable: true
  7702. });
  7703. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7704. get: function () {
  7705. return Engine._DELAYLOADSTATE_NOTLOADED;
  7706. },
  7707. enumerable: true,
  7708. configurable: true
  7709. });
  7710. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7711. get: function () {
  7712. return Engine._TEXTUREFORMAT_ALPHA;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7718. get: function () {
  7719. return Engine._TEXTUREFORMAT_LUMINANCE;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7725. get: function () {
  7726. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7732. get: function () {
  7733. return Engine._TEXTUREFORMAT_RGB;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7739. get: function () {
  7740. return Engine._TEXTUREFORMAT_RGBA;
  7741. },
  7742. enumerable: true,
  7743. configurable: true
  7744. });
  7745. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7746. get: function () {
  7747. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7748. },
  7749. enumerable: true,
  7750. configurable: true
  7751. });
  7752. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7753. get: function () {
  7754. return Engine._TEXTURETYPE_FLOAT;
  7755. },
  7756. enumerable: true,
  7757. configurable: true
  7758. });
  7759. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7760. get: function () {
  7761. return Engine._TEXTURETYPE_HALF_FLOAT;
  7762. },
  7763. enumerable: true,
  7764. configurable: true
  7765. });
  7766. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7767. get: function () {
  7768. return Engine._SCALEMODE_FLOOR;
  7769. },
  7770. enumerable: true,
  7771. configurable: true
  7772. });
  7773. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7774. get: function () {
  7775. return Engine._SCALEMODE_NEAREST;
  7776. },
  7777. enumerable: true,
  7778. configurable: true
  7779. });
  7780. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7781. get: function () {
  7782. return Engine._SCALEMODE_CEILING;
  7783. },
  7784. enumerable: true,
  7785. configurable: true
  7786. });
  7787. Object.defineProperty(Engine, "Version", {
  7788. get: function () {
  7789. return "3.0-rc";
  7790. },
  7791. enumerable: true,
  7792. configurable: true
  7793. });
  7794. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7795. get: function () {
  7796. return this._texturesSupported;
  7797. },
  7798. enumerable: true,
  7799. configurable: true
  7800. });
  7801. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7802. get: function () {
  7803. return this._textureFormatInUse;
  7804. },
  7805. enumerable: true,
  7806. configurable: true
  7807. });
  7808. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7809. // Empty texture
  7810. get: function () {
  7811. if (!this._emptyTexture) {
  7812. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7813. }
  7814. return this._emptyTexture;
  7815. },
  7816. enumerable: true,
  7817. configurable: true
  7818. });
  7819. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7820. get: function () {
  7821. if (!this._emptyCubeTexture) {
  7822. var faceData = new Uint8Array(4);
  7823. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7824. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7825. }
  7826. return this._emptyCubeTexture;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7832. get: function () {
  7833. return this._webGLVersion;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7839. /**
  7840. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7841. */
  7842. get: function () {
  7843. return this._isStencilEnable;
  7844. },
  7845. enumerable: true,
  7846. configurable: true
  7847. });
  7848. Engine.prototype._prepareWorkingCanvas = function () {
  7849. if (this._workingCanvas) {
  7850. return;
  7851. }
  7852. this._workingCanvas = document.createElement("canvas");
  7853. this._workingContext = this._workingCanvas.getContext("2d");
  7854. };
  7855. Engine.prototype.resetTextureCache = function () {
  7856. for (var index = 0; index < this._maxTextureChannels; index++) {
  7857. this._activeTexturesCache[index] = null;
  7858. }
  7859. };
  7860. Engine.prototype.getGlInfo = function () {
  7861. return {
  7862. vendor: this._glVendor,
  7863. renderer: this._glRenderer,
  7864. version: this._glVersion
  7865. };
  7866. };
  7867. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7868. if (useScreen === void 0) { useScreen = false; }
  7869. var viewport = camera.viewport;
  7870. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7871. };
  7872. Engine.prototype.getRenderWidth = function (useScreen) {
  7873. if (useScreen === void 0) { useScreen = false; }
  7874. if (!useScreen && this._currentRenderTarget) {
  7875. return this._currentRenderTarget._width;
  7876. }
  7877. return this._renderingCanvas.width;
  7878. };
  7879. Engine.prototype.getRenderHeight = function (useScreen) {
  7880. if (useScreen === void 0) { useScreen = false; }
  7881. if (!useScreen && this._currentRenderTarget) {
  7882. return this._currentRenderTarget._height;
  7883. }
  7884. return this._renderingCanvas.height;
  7885. };
  7886. Engine.prototype.getRenderingCanvas = function () {
  7887. return this._renderingCanvas;
  7888. };
  7889. Engine.prototype.getRenderingCanvasClientRect = function () {
  7890. return this._renderingCanvas.getBoundingClientRect();
  7891. };
  7892. Engine.prototype.setHardwareScalingLevel = function (level) {
  7893. this._hardwareScalingLevel = level;
  7894. this.resize();
  7895. };
  7896. Engine.prototype.getHardwareScalingLevel = function () {
  7897. return this._hardwareScalingLevel;
  7898. };
  7899. Engine.prototype.getLoadedTexturesCache = function () {
  7900. return this._loadedTexturesCache;
  7901. };
  7902. Engine.prototype.getCaps = function () {
  7903. return this._caps;
  7904. };
  7905. Object.defineProperty(Engine.prototype, "drawCalls", {
  7906. get: function () {
  7907. return this._drawCalls.current;
  7908. },
  7909. enumerable: true,
  7910. configurable: true
  7911. });
  7912. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7913. get: function () {
  7914. return this._drawCalls;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Engine.prototype.getDepthFunction = function () {
  7920. return this._depthCullingState.depthFunc;
  7921. };
  7922. Engine.prototype.setDepthFunction = function (depthFunc) {
  7923. this._depthCullingState.depthFunc = depthFunc;
  7924. };
  7925. Engine.prototype.setDepthFunctionToGreater = function () {
  7926. this._depthCullingState.depthFunc = this._gl.GREATER;
  7927. };
  7928. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7929. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7930. };
  7931. Engine.prototype.setDepthFunctionToLess = function () {
  7932. this._depthCullingState.depthFunc = this._gl.LESS;
  7933. };
  7934. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7935. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7936. };
  7937. Engine.prototype.getStencilBuffer = function () {
  7938. return this._stencilState.stencilTest;
  7939. };
  7940. Engine.prototype.setStencilBuffer = function (enable) {
  7941. this._stencilState.stencilTest = enable;
  7942. };
  7943. Engine.prototype.getStencilMask = function () {
  7944. return this._stencilState.stencilMask;
  7945. };
  7946. Engine.prototype.setStencilMask = function (mask) {
  7947. this._stencilState.stencilMask = mask;
  7948. };
  7949. Engine.prototype.getStencilFunction = function () {
  7950. return this._stencilState.stencilFunc;
  7951. };
  7952. Engine.prototype.getStencilFunctionReference = function () {
  7953. return this._stencilState.stencilFuncRef;
  7954. };
  7955. Engine.prototype.getStencilFunctionMask = function () {
  7956. return this._stencilState.stencilFuncMask;
  7957. };
  7958. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7959. this._stencilState.stencilFunc = stencilFunc;
  7960. };
  7961. Engine.prototype.setStencilFunctionReference = function (reference) {
  7962. this._stencilState.stencilFuncRef = reference;
  7963. };
  7964. Engine.prototype.setStencilFunctionMask = function (mask) {
  7965. this._stencilState.stencilFuncMask = mask;
  7966. };
  7967. Engine.prototype.getStencilOperationFail = function () {
  7968. return this._stencilState.stencilOpStencilFail;
  7969. };
  7970. Engine.prototype.getStencilOperationDepthFail = function () {
  7971. return this._stencilState.stencilOpDepthFail;
  7972. };
  7973. Engine.prototype.getStencilOperationPass = function () {
  7974. return this._stencilState.stencilOpStencilDepthPass;
  7975. };
  7976. Engine.prototype.setStencilOperationFail = function (operation) {
  7977. this._stencilState.stencilOpStencilFail = operation;
  7978. };
  7979. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7980. this._stencilState.stencilOpDepthFail = operation;
  7981. };
  7982. Engine.prototype.setStencilOperationPass = function (operation) {
  7983. this._stencilState.stencilOpStencilDepthPass = operation;
  7984. };
  7985. Engine.prototype.setDitheringState = function (value) {
  7986. if (value) {
  7987. this._gl.enable(this._gl.DITHER);
  7988. }
  7989. else {
  7990. this._gl.disable(this._gl.DITHER);
  7991. }
  7992. };
  7993. /**
  7994. * stop executing a render loop function and remove it from the execution array
  7995. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7996. */
  7997. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7998. if (!renderFunction) {
  7999. this._activeRenderLoops = [];
  8000. return;
  8001. }
  8002. var index = this._activeRenderLoops.indexOf(renderFunction);
  8003. if (index >= 0) {
  8004. this._activeRenderLoops.splice(index, 1);
  8005. }
  8006. };
  8007. Engine.prototype._renderLoop = function () {
  8008. var shouldRender = true;
  8009. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8010. shouldRender = false;
  8011. }
  8012. if (shouldRender) {
  8013. // Start new frame
  8014. this.beginFrame();
  8015. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8016. var renderFunction = this._activeRenderLoops[index];
  8017. renderFunction();
  8018. }
  8019. // Present
  8020. this.endFrame();
  8021. }
  8022. if (this._activeRenderLoops.length > 0) {
  8023. // Register new frame
  8024. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8025. }
  8026. else {
  8027. this._renderingQueueLaunched = false;
  8028. }
  8029. };
  8030. /**
  8031. * Register and execute a render loop. The engine can have more than one render function.
  8032. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8033. * @example
  8034. * engine.runRenderLoop(function () {
  8035. * scene.render()
  8036. * })
  8037. */
  8038. Engine.prototype.runRenderLoop = function (renderFunction) {
  8039. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8040. return;
  8041. }
  8042. this._activeRenderLoops.push(renderFunction);
  8043. if (!this._renderingQueueLaunched) {
  8044. this._renderingQueueLaunched = true;
  8045. this._bindedRenderFunction = this._renderLoop.bind(this);
  8046. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8047. }
  8048. };
  8049. /**
  8050. * Toggle full screen mode.
  8051. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8052. * @param {any} options - an options object to be sent to the requestFullscreen function
  8053. */
  8054. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8055. if (this.isFullscreen) {
  8056. BABYLON.Tools.ExitFullscreen();
  8057. }
  8058. else {
  8059. this._pointerLockRequested = requestPointerLock;
  8060. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8061. }
  8062. };
  8063. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8064. if (stencil === void 0) { stencil = false; }
  8065. this.applyStates();
  8066. var mode = 0;
  8067. if (backBuffer && color) {
  8068. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8069. mode |= this._gl.COLOR_BUFFER_BIT;
  8070. }
  8071. if (depth) {
  8072. this._gl.clearDepth(1.0);
  8073. mode |= this._gl.DEPTH_BUFFER_BIT;
  8074. }
  8075. if (stencil) {
  8076. this._gl.clearStencil(0);
  8077. mode |= this._gl.STENCIL_BUFFER_BIT;
  8078. }
  8079. this._gl.clear(mode);
  8080. };
  8081. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8082. var gl = this._gl;
  8083. // Save state
  8084. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8085. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8086. // Change state
  8087. gl.enable(gl.SCISSOR_TEST);
  8088. gl.scissor(x, y, width, height);
  8089. // Clear
  8090. this.clear(clearColor, true, true, true);
  8091. // Restore state
  8092. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8093. if (curScissor === true) {
  8094. gl.enable(gl.SCISSOR_TEST);
  8095. }
  8096. else {
  8097. gl.disable(gl.SCISSOR_TEST);
  8098. }
  8099. };
  8100. /**
  8101. * Set the WebGL's viewport
  8102. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8103. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8104. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8105. */
  8106. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8107. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8108. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8109. var x = viewport.x || 0;
  8110. var y = viewport.y || 0;
  8111. this._cachedViewport = viewport;
  8112. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8113. };
  8114. /**
  8115. * Directly set the WebGL Viewport
  8116. * The x, y, width & height are directly passed to the WebGL call
  8117. * @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.
  8118. */
  8119. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8120. var currentViewport = this._cachedViewport;
  8121. this._cachedViewport = null;
  8122. this._gl.viewport(x, y, width, height);
  8123. return currentViewport;
  8124. };
  8125. Engine.prototype.beginFrame = function () {
  8126. this._measureFps();
  8127. };
  8128. Engine.prototype.endFrame = function () {
  8129. //force a flush in case we are using a bad OS.
  8130. if (this._badOS) {
  8131. this.flushFramebuffer();
  8132. }
  8133. //submit frame to the vr device, if enabled
  8134. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8135. this._vrDisplayEnabled.submitFrame();
  8136. }
  8137. };
  8138. /**
  8139. * resize the view according to the canvas' size.
  8140. * @example
  8141. * window.addEventListener("resize", function () {
  8142. * engine.resize();
  8143. * });
  8144. */
  8145. Engine.prototype.resize = function () {
  8146. // We're not resizing the size of the canvas while in VR mode & presenting
  8147. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8148. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8149. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8150. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8151. }
  8152. };
  8153. /**
  8154. * force a specific size of the canvas
  8155. * @param {number} width - the new canvas' width
  8156. * @param {number} height - the new canvas' height
  8157. */
  8158. Engine.prototype.setSize = function (width, height) {
  8159. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8160. return;
  8161. }
  8162. this._renderingCanvas.width = width;
  8163. this._renderingCanvas.height = height;
  8164. for (var index = 0; index < this.scenes.length; index++) {
  8165. var scene = this.scenes[index];
  8166. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8167. var cam = scene.cameras[camIndex];
  8168. cam._currentRenderId = 0;
  8169. }
  8170. }
  8171. if (this.onResizeObservable.hasObservers) {
  8172. this.onResizeObservable.notifyObservers(this);
  8173. }
  8174. };
  8175. //WebVR functions
  8176. Engine.prototype.isVRDevicePresent = function (callback) {
  8177. this.getVRDevice(null, function (device) {
  8178. callback(device !== null);
  8179. });
  8180. };
  8181. Engine.prototype.getVRDevice = function (name, callback) {
  8182. if (!this.vrDisplaysPromise) {
  8183. callback(null);
  8184. return;
  8185. }
  8186. this.vrDisplaysPromise.then(function (devices) {
  8187. if (devices.length > 0) {
  8188. if (name) {
  8189. var found = devices.some(function (device) {
  8190. if (device.displayName === name) {
  8191. callback(device);
  8192. return true;
  8193. }
  8194. else {
  8195. return false;
  8196. }
  8197. });
  8198. if (!found) {
  8199. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8200. callback(devices[0]);
  8201. }
  8202. }
  8203. else {
  8204. //choose the first one
  8205. callback(devices[0]);
  8206. }
  8207. }
  8208. else {
  8209. BABYLON.Tools.Error("No WebVR devices found!");
  8210. callback(null);
  8211. }
  8212. });
  8213. };
  8214. Engine.prototype.initWebVR = function () {
  8215. if (!this.vrDisplaysPromise) {
  8216. this._getVRDisplays();
  8217. }
  8218. };
  8219. Engine.prototype.enableVR = function (vrDevice) {
  8220. this._vrDisplayEnabled = vrDevice;
  8221. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8222. };
  8223. Engine.prototype.disableVR = function () {
  8224. if (this._vrDisplayEnabled) {
  8225. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8226. }
  8227. };
  8228. Engine.prototype._getVRDisplays = function () {
  8229. var _this = this;
  8230. var getWebVRDevices = function (devices) {
  8231. var size = devices.length;
  8232. var i = 0;
  8233. _this._vrDisplays = devices.filter(function (device) {
  8234. return devices[i] instanceof VRDisplay;
  8235. });
  8236. return _this._vrDisplays;
  8237. };
  8238. //using a key due to typescript
  8239. if (navigator.getVRDisplays) {
  8240. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8241. }
  8242. };
  8243. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8244. this._currentRenderTarget = texture;
  8245. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8246. var gl = this._gl;
  8247. if (texture.isCube) {
  8248. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8249. }
  8250. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8251. this.wipeCaches();
  8252. };
  8253. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8254. if (this._currentFramebuffer !== framebuffer) {
  8255. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8256. this._currentFramebuffer = framebuffer;
  8257. }
  8258. };
  8259. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8260. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8261. this._currentRenderTarget = null;
  8262. // If MSAA, we need to bitblt back to main texture
  8263. var gl = this._gl;
  8264. if (texture._MSAAFramebuffer) {
  8265. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8266. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8267. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8268. }
  8269. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8270. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8271. gl.generateMipmap(gl.TEXTURE_2D);
  8272. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8273. }
  8274. if (onBeforeUnbind) {
  8275. if (texture._MSAAFramebuffer) {
  8276. // Bind the correct framebuffer
  8277. this.bindUnboundFramebuffer(texture._framebuffer);
  8278. }
  8279. onBeforeUnbind();
  8280. }
  8281. this.bindUnboundFramebuffer(null);
  8282. };
  8283. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8284. if (texture.generateMipMaps) {
  8285. var gl = this._gl;
  8286. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8287. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8288. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8289. }
  8290. };
  8291. Engine.prototype.flushFramebuffer = function () {
  8292. this._gl.flush();
  8293. };
  8294. Engine.prototype.restoreDefaultFramebuffer = function () {
  8295. this._currentRenderTarget = null;
  8296. this.bindUnboundFramebuffer(null);
  8297. if (this._cachedViewport) {
  8298. this.setViewport(this._cachedViewport);
  8299. }
  8300. this.wipeCaches();
  8301. };
  8302. // UBOs
  8303. Engine.prototype.createUniformBuffer = function (elements) {
  8304. var ubo = this._gl.createBuffer();
  8305. this.bindUniformBuffer(ubo);
  8306. if (elements instanceof Float32Array) {
  8307. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8308. }
  8309. else {
  8310. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8311. }
  8312. this.bindUniformBuffer(null);
  8313. ubo.references = 1;
  8314. return ubo;
  8315. };
  8316. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8317. var ubo = this._gl.createBuffer();
  8318. this.bindUniformBuffer(ubo);
  8319. if (elements instanceof Float32Array) {
  8320. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8321. }
  8322. else {
  8323. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8324. }
  8325. this.bindUniformBuffer(null);
  8326. ubo.references = 1;
  8327. return ubo;
  8328. };
  8329. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8330. this.bindUniformBuffer(uniformBuffer);
  8331. if (offset === undefined) {
  8332. offset = 0;
  8333. }
  8334. if (count === undefined) {
  8335. if (elements instanceof Float32Array) {
  8336. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8337. }
  8338. else {
  8339. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8340. }
  8341. }
  8342. else {
  8343. if (elements instanceof Float32Array) {
  8344. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8345. }
  8346. else {
  8347. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8348. }
  8349. }
  8350. this.bindUniformBuffer(null);
  8351. };
  8352. // VBOs
  8353. Engine.prototype._resetVertexBufferBinding = function () {
  8354. this.bindArrayBuffer(null);
  8355. this._cachedVertexBuffers = null;
  8356. };
  8357. Engine.prototype.createVertexBuffer = function (vertices) {
  8358. var vbo = this._gl.createBuffer();
  8359. this.bindArrayBuffer(vbo);
  8360. if (vertices instanceof Float32Array) {
  8361. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8362. }
  8363. else {
  8364. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8365. }
  8366. this._resetVertexBufferBinding();
  8367. vbo.references = 1;
  8368. return vbo;
  8369. };
  8370. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8371. var vbo = this._gl.createBuffer();
  8372. this.bindArrayBuffer(vbo);
  8373. if (vertices instanceof Float32Array) {
  8374. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8375. }
  8376. else {
  8377. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8378. }
  8379. this._resetVertexBufferBinding();
  8380. vbo.references = 1;
  8381. return vbo;
  8382. };
  8383. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8384. this.bindArrayBuffer(vertexBuffer);
  8385. if (offset === undefined) {
  8386. offset = 0;
  8387. }
  8388. if (count === undefined) {
  8389. if (vertices instanceof Float32Array) {
  8390. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8391. }
  8392. else {
  8393. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8394. }
  8395. }
  8396. else {
  8397. if (vertices instanceof Float32Array) {
  8398. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8399. }
  8400. else {
  8401. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8402. }
  8403. }
  8404. this._resetVertexBufferBinding();
  8405. };
  8406. Engine.prototype._resetIndexBufferBinding = function () {
  8407. this.bindIndexBuffer(null);
  8408. this._cachedIndexBuffer = null;
  8409. };
  8410. Engine.prototype.createIndexBuffer = function (indices) {
  8411. var vbo = this._gl.createBuffer();
  8412. this.bindIndexBuffer(vbo);
  8413. // Check for 32 bits indices
  8414. var arrayBuffer;
  8415. var need32Bits = false;
  8416. if (indices instanceof Uint16Array) {
  8417. arrayBuffer = indices;
  8418. }
  8419. else {
  8420. //check 32 bit support
  8421. if (this._caps.uintIndices) {
  8422. if (indices instanceof Uint32Array) {
  8423. arrayBuffer = indices;
  8424. need32Bits = true;
  8425. }
  8426. else {
  8427. //number[] or Int32Array, check if 32 bit is necessary
  8428. for (var index = 0; index < indices.length; index++) {
  8429. if (indices[index] > 65535) {
  8430. need32Bits = true;
  8431. break;
  8432. }
  8433. }
  8434. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8435. }
  8436. }
  8437. else {
  8438. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8439. arrayBuffer = new Uint16Array(indices);
  8440. }
  8441. }
  8442. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8443. this._resetIndexBufferBinding();
  8444. vbo.references = 1;
  8445. vbo.is32Bits = need32Bits;
  8446. return vbo;
  8447. };
  8448. Engine.prototype.bindArrayBuffer = function (buffer) {
  8449. if (!this._vaoRecordInProgress) {
  8450. this._unBindVertexArrayObject();
  8451. }
  8452. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8453. };
  8454. Engine.prototype.bindUniformBuffer = function (buffer) {
  8455. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8456. };
  8457. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8458. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8459. };
  8460. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8461. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8462. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8463. };
  8464. ;
  8465. Engine.prototype.bindIndexBuffer = function (buffer) {
  8466. if (!this._vaoRecordInProgress) {
  8467. this._unBindVertexArrayObject();
  8468. }
  8469. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8470. };
  8471. Engine.prototype.bindBuffer = function (buffer, target) {
  8472. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8473. this._gl.bindBuffer(target, buffer);
  8474. this._currentBoundBuffer[target] = buffer;
  8475. }
  8476. };
  8477. Engine.prototype.updateArrayBuffer = function (data) {
  8478. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8479. };
  8480. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8481. var pointer = this._currentBufferPointers[indx];
  8482. var changed = false;
  8483. if (!pointer) {
  8484. changed = true;
  8485. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8486. }
  8487. else {
  8488. if (pointer.buffer !== buffer) {
  8489. pointer.buffer = buffer;
  8490. changed = true;
  8491. }
  8492. if (pointer.size !== size) {
  8493. pointer.size = size;
  8494. changed = true;
  8495. }
  8496. if (pointer.type !== type) {
  8497. pointer.type = type;
  8498. changed = true;
  8499. }
  8500. if (pointer.normalized !== normalized) {
  8501. pointer.normalized = normalized;
  8502. changed = true;
  8503. }
  8504. if (pointer.stride !== stride) {
  8505. pointer.stride = stride;
  8506. changed = true;
  8507. }
  8508. if (pointer.offset !== offset) {
  8509. pointer.offset = offset;
  8510. changed = true;
  8511. }
  8512. }
  8513. if (changed || this._vaoRecordInProgress) {
  8514. this.bindArrayBuffer(buffer);
  8515. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8516. }
  8517. };
  8518. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8519. if (indexBuffer == null) {
  8520. return;
  8521. }
  8522. if (this._cachedIndexBuffer !== indexBuffer) {
  8523. this._cachedIndexBuffer = indexBuffer;
  8524. this.bindIndexBuffer(indexBuffer);
  8525. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8526. }
  8527. };
  8528. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8529. var attributes = effect.getAttributesNames();
  8530. if (!this._vaoRecordInProgress) {
  8531. this._unBindVertexArrayObject();
  8532. }
  8533. this.unbindAllAttributes();
  8534. for (var index = 0; index < attributes.length; index++) {
  8535. var order = effect.getAttributeLocation(index);
  8536. if (order >= 0) {
  8537. var vertexBuffer = vertexBuffers[attributes[index]];
  8538. if (!vertexBuffer) {
  8539. continue;
  8540. }
  8541. this._gl.enableVertexAttribArray(order);
  8542. if (!this._vaoRecordInProgress) {
  8543. this._vertexAttribArraysEnabled[order] = true;
  8544. }
  8545. var buffer = vertexBuffer.getBuffer();
  8546. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8547. if (vertexBuffer.getIsInstanced()) {
  8548. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8549. if (!this._vaoRecordInProgress) {
  8550. this._currentInstanceLocations.push(order);
  8551. this._currentInstanceBuffers.push(buffer);
  8552. }
  8553. }
  8554. }
  8555. }
  8556. };
  8557. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8558. var vao = this._gl.createVertexArray();
  8559. this._vaoRecordInProgress = true;
  8560. this._gl.bindVertexArray(vao);
  8561. this._mustWipeVertexAttributes = true;
  8562. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8563. this.bindIndexBuffer(indexBuffer);
  8564. this._vaoRecordInProgress = false;
  8565. this._gl.bindVertexArray(null);
  8566. return vao;
  8567. };
  8568. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8569. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8570. this._cachedVertexArrayObject = vertexArrayObject;
  8571. this._gl.bindVertexArray(vertexArrayObject);
  8572. this._cachedVertexBuffers = null;
  8573. this._cachedIndexBuffer = null;
  8574. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8575. this._mustWipeVertexAttributes = true;
  8576. }
  8577. };
  8578. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8579. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8580. this._cachedVertexBuffers = vertexBuffer;
  8581. this._cachedEffectForVertexBuffers = effect;
  8582. var attributesCount = effect.getAttributesCount();
  8583. this._unBindVertexArrayObject();
  8584. this.unbindAllAttributes();
  8585. var offset = 0;
  8586. for (var index = 0; index < attributesCount; index++) {
  8587. if (index < vertexDeclaration.length) {
  8588. var order = effect.getAttributeLocation(index);
  8589. if (order >= 0) {
  8590. this._gl.enableVertexAttribArray(order);
  8591. this._vertexAttribArraysEnabled[order] = true;
  8592. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8593. }
  8594. offset += vertexDeclaration[index] * 4;
  8595. }
  8596. }
  8597. }
  8598. this._bindIndexBufferWithCache(indexBuffer);
  8599. };
  8600. Engine.prototype._unBindVertexArrayObject = function () {
  8601. if (!this._cachedVertexArrayObject) {
  8602. return;
  8603. }
  8604. this._cachedVertexArrayObject = null;
  8605. this._gl.bindVertexArray(null);
  8606. };
  8607. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8608. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8609. this._cachedVertexBuffers = vertexBuffers;
  8610. this._cachedEffectForVertexBuffers = effect;
  8611. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8612. }
  8613. this._bindIndexBufferWithCache(indexBuffer);
  8614. };
  8615. Engine.prototype.unbindInstanceAttributes = function () {
  8616. var boundBuffer;
  8617. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8618. var instancesBuffer = this._currentInstanceBuffers[i];
  8619. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8620. boundBuffer = instancesBuffer;
  8621. this.bindArrayBuffer(instancesBuffer);
  8622. }
  8623. var offsetLocation = this._currentInstanceLocations[i];
  8624. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8625. }
  8626. this._currentInstanceBuffers.length = 0;
  8627. this._currentInstanceLocations.length = 0;
  8628. };
  8629. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8630. this._gl.deleteVertexArray(vao);
  8631. };
  8632. Engine.prototype._releaseBuffer = function (buffer) {
  8633. buffer.references--;
  8634. if (buffer.references === 0) {
  8635. this._gl.deleteBuffer(buffer);
  8636. return true;
  8637. }
  8638. return false;
  8639. };
  8640. Engine.prototype.createInstancesBuffer = function (capacity) {
  8641. var buffer = this._gl.createBuffer();
  8642. buffer.capacity = capacity;
  8643. this.bindArrayBuffer(buffer);
  8644. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8645. return buffer;
  8646. };
  8647. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8648. this._gl.deleteBuffer(buffer);
  8649. };
  8650. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8651. this.bindArrayBuffer(instancesBuffer);
  8652. if (data) {
  8653. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8654. }
  8655. if (offsetLocations[0].index !== undefined) {
  8656. var stride = 0;
  8657. for (var i = 0; i < offsetLocations.length; i++) {
  8658. var ai = offsetLocations[i];
  8659. stride += ai.attributeSize * 4;
  8660. }
  8661. for (var i = 0; i < offsetLocations.length; i++) {
  8662. var ai = offsetLocations[i];
  8663. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8664. this._gl.enableVertexAttribArray(ai.index);
  8665. this._vertexAttribArraysEnabled[ai.index] = true;
  8666. }
  8667. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8668. this._gl.vertexAttribDivisor(ai.index, 1);
  8669. this._currentInstanceLocations.push(ai.index);
  8670. this._currentInstanceBuffers.push(instancesBuffer);
  8671. }
  8672. }
  8673. else {
  8674. for (var index = 0; index < 4; index++) {
  8675. var offsetLocation = offsetLocations[index];
  8676. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8677. this._gl.enableVertexAttribArray(offsetLocation);
  8678. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8679. }
  8680. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8681. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8682. this._currentInstanceLocations.push(offsetLocation);
  8683. this._currentInstanceBuffers.push(instancesBuffer);
  8684. }
  8685. }
  8686. };
  8687. Engine.prototype.applyStates = function () {
  8688. this._depthCullingState.apply(this._gl);
  8689. this._stencilState.apply(this._gl);
  8690. this._alphaState.apply(this._gl);
  8691. };
  8692. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8693. // Apply states
  8694. this.applyStates();
  8695. this._drawCalls.addCount(1, false);
  8696. // Render
  8697. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8698. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8699. if (instancesCount) {
  8700. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8701. return;
  8702. }
  8703. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8704. };
  8705. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8706. // Apply states
  8707. this.applyStates();
  8708. this._drawCalls.addCount(1, false);
  8709. if (instancesCount) {
  8710. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8711. return;
  8712. }
  8713. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8714. };
  8715. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8716. // Apply states
  8717. this.applyStates();
  8718. this._drawCalls.addCount(1, false);
  8719. if (instancesCount) {
  8720. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8721. return;
  8722. }
  8723. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8724. };
  8725. // Shaders
  8726. Engine.prototype._releaseEffect = function (effect) {
  8727. if (this._compiledEffects[effect._key]) {
  8728. delete this._compiledEffects[effect._key];
  8729. if (effect.getProgram()) {
  8730. this._gl.deleteProgram(effect.getProgram());
  8731. }
  8732. }
  8733. };
  8734. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8735. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8736. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8737. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8738. if (this._compiledEffects[name]) {
  8739. var compiledEffect = this._compiledEffects[name];
  8740. if (onCompiled && compiledEffect.isReady()) {
  8741. onCompiled(compiledEffect);
  8742. }
  8743. return compiledEffect;
  8744. }
  8745. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8746. effect._key = name;
  8747. this._compiledEffects[name] = effect;
  8748. return effect;
  8749. };
  8750. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8751. if (uniformsNames === void 0) { uniformsNames = []; }
  8752. if (samplers === void 0) { samplers = []; }
  8753. if (defines === void 0) { defines = ""; }
  8754. return this.createEffect({
  8755. vertex: "particles",
  8756. fragmentElement: fragmentName
  8757. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8758. };
  8759. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8760. context = context || this._gl;
  8761. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8762. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8763. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8764. var shaderProgram = context.createProgram();
  8765. context.attachShader(shaderProgram, vertexShader);
  8766. context.attachShader(shaderProgram, fragmentShader);
  8767. context.linkProgram(shaderProgram);
  8768. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8769. if (!linked) {
  8770. var error = context.getProgramInfoLog(shaderProgram);
  8771. if (error) {
  8772. throw new Error(error);
  8773. }
  8774. }
  8775. context.deleteShader(vertexShader);
  8776. context.deleteShader(fragmentShader);
  8777. return shaderProgram;
  8778. };
  8779. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8780. var results = [];
  8781. for (var index = 0; index < uniformsNames.length; index++) {
  8782. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8783. }
  8784. return results;
  8785. };
  8786. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8787. var results = [];
  8788. for (var index = 0; index < attributesNames.length; index++) {
  8789. try {
  8790. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8791. }
  8792. catch (e) {
  8793. results.push(-1);
  8794. }
  8795. }
  8796. return results;
  8797. };
  8798. Engine.prototype.enableEffect = function (effect) {
  8799. // Use program
  8800. this.setProgram(effect.getProgram());
  8801. this._currentEffect = effect;
  8802. if (effect.onBind) {
  8803. effect.onBind(effect);
  8804. }
  8805. effect.onBindObservable.notifyObservers(effect);
  8806. };
  8807. Engine.prototype.setIntArray = function (uniform, array) {
  8808. if (!uniform)
  8809. return;
  8810. this._gl.uniform1iv(uniform, array);
  8811. };
  8812. Engine.prototype.setIntArray2 = function (uniform, array) {
  8813. if (!uniform || array.length % 2 !== 0)
  8814. return;
  8815. this._gl.uniform2iv(uniform, array);
  8816. };
  8817. Engine.prototype.setIntArray3 = function (uniform, array) {
  8818. if (!uniform || array.length % 3 !== 0)
  8819. return;
  8820. this._gl.uniform3iv(uniform, array);
  8821. };
  8822. Engine.prototype.setIntArray4 = function (uniform, array) {
  8823. if (!uniform || array.length % 4 !== 0)
  8824. return;
  8825. this._gl.uniform4iv(uniform, array);
  8826. };
  8827. Engine.prototype.setFloatArray = function (uniform, array) {
  8828. if (!uniform)
  8829. return;
  8830. this._gl.uniform1fv(uniform, array);
  8831. };
  8832. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8833. if (!uniform || array.length % 2 !== 0)
  8834. return;
  8835. this._gl.uniform2fv(uniform, array);
  8836. };
  8837. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8838. if (!uniform || array.length % 3 !== 0)
  8839. return;
  8840. this._gl.uniform3fv(uniform, array);
  8841. };
  8842. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8843. if (!uniform || array.length % 4 !== 0)
  8844. return;
  8845. this._gl.uniform4fv(uniform, array);
  8846. };
  8847. Engine.prototype.setArray = function (uniform, array) {
  8848. if (!uniform)
  8849. return;
  8850. this._gl.uniform1fv(uniform, array);
  8851. };
  8852. Engine.prototype.setArray2 = function (uniform, array) {
  8853. if (!uniform || array.length % 2 !== 0)
  8854. return;
  8855. this._gl.uniform2fv(uniform, array);
  8856. };
  8857. Engine.prototype.setArray3 = function (uniform, array) {
  8858. if (!uniform || array.length % 3 !== 0)
  8859. return;
  8860. this._gl.uniform3fv(uniform, array);
  8861. };
  8862. Engine.prototype.setArray4 = function (uniform, array) {
  8863. if (!uniform || array.length % 4 !== 0)
  8864. return;
  8865. this._gl.uniform4fv(uniform, array);
  8866. };
  8867. Engine.prototype.setMatrices = function (uniform, matrices) {
  8868. if (!uniform)
  8869. return;
  8870. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8871. };
  8872. Engine.prototype.setMatrix = function (uniform, matrix) {
  8873. if (!uniform)
  8874. return;
  8875. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8876. };
  8877. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8878. if (!uniform)
  8879. return;
  8880. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8881. };
  8882. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8883. if (!uniform)
  8884. return;
  8885. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8886. };
  8887. Engine.prototype.setFloat = function (uniform, value) {
  8888. if (!uniform)
  8889. return;
  8890. this._gl.uniform1f(uniform, value);
  8891. };
  8892. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8893. if (!uniform)
  8894. return;
  8895. this._gl.uniform2f(uniform, x, y);
  8896. };
  8897. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8898. if (!uniform)
  8899. return;
  8900. this._gl.uniform3f(uniform, x, y, z);
  8901. };
  8902. Engine.prototype.setBool = function (uniform, bool) {
  8903. if (!uniform)
  8904. return;
  8905. this._gl.uniform1i(uniform, bool);
  8906. };
  8907. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8908. if (!uniform)
  8909. return;
  8910. this._gl.uniform4f(uniform, x, y, z, w);
  8911. };
  8912. Engine.prototype.setColor3 = function (uniform, color3) {
  8913. if (!uniform)
  8914. return;
  8915. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8916. };
  8917. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8918. if (!uniform)
  8919. return;
  8920. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8921. };
  8922. // States
  8923. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8924. if (zOffset === void 0) { zOffset = 0; }
  8925. if (reverseSide === void 0) { reverseSide = false; }
  8926. // Culling
  8927. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8928. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8929. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8930. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8931. if (culling) {
  8932. this._depthCullingState.cullFace = cullFace;
  8933. this._depthCullingState.cull = true;
  8934. }
  8935. else {
  8936. this._depthCullingState.cull = false;
  8937. }
  8938. }
  8939. // Z offset
  8940. this.setZOffset(zOffset);
  8941. };
  8942. Engine.prototype.setZOffset = function (value) {
  8943. this._depthCullingState.zOffset = value;
  8944. };
  8945. Engine.prototype.getZOffset = function () {
  8946. return this._depthCullingState.zOffset;
  8947. };
  8948. Engine.prototype.setDepthBuffer = function (enable) {
  8949. this._depthCullingState.depthTest = enable;
  8950. };
  8951. Engine.prototype.getDepthWrite = function () {
  8952. return this._depthCullingState.depthMask;
  8953. };
  8954. Engine.prototype.setDepthWrite = function (enable) {
  8955. this._depthCullingState.depthMask = enable;
  8956. };
  8957. Engine.prototype.setColorWrite = function (enable) {
  8958. this._gl.colorMask(enable, enable, enable, enable);
  8959. };
  8960. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8961. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8962. };
  8963. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8964. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8965. if (this._alphaMode === mode) {
  8966. return;
  8967. }
  8968. switch (mode) {
  8969. case Engine.ALPHA_DISABLE:
  8970. this._alphaState.alphaBlend = false;
  8971. break;
  8972. case Engine.ALPHA_PREMULTIPLIED:
  8973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8974. this._alphaState.alphaBlend = true;
  8975. break;
  8976. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8978. this._alphaState.alphaBlend = true;
  8979. break;
  8980. case Engine.ALPHA_COMBINE:
  8981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8982. this._alphaState.alphaBlend = true;
  8983. break;
  8984. case Engine.ALPHA_ONEONE:
  8985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8986. this._alphaState.alphaBlend = true;
  8987. break;
  8988. case Engine.ALPHA_ADD:
  8989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8990. this._alphaState.alphaBlend = true;
  8991. break;
  8992. case Engine.ALPHA_SUBTRACT:
  8993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8994. this._alphaState.alphaBlend = true;
  8995. break;
  8996. case Engine.ALPHA_MULTIPLY:
  8997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8998. this._alphaState.alphaBlend = true;
  8999. break;
  9000. case Engine.ALPHA_MAXIMIZED:
  9001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9002. this._alphaState.alphaBlend = true;
  9003. break;
  9004. case Engine.ALPHA_INTERPOLATE:
  9005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9006. this._alphaState.alphaBlend = true;
  9007. break;
  9008. case Engine.ALPHA_SCREENMODE:
  9009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9010. this._alphaState.alphaBlend = true;
  9011. break;
  9012. }
  9013. if (!noDepthWriteChange) {
  9014. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9015. }
  9016. this._alphaMode = mode;
  9017. };
  9018. Engine.prototype.getAlphaMode = function () {
  9019. return this._alphaMode;
  9020. };
  9021. Engine.prototype.setAlphaTesting = function (enable) {
  9022. this._alphaTest = enable;
  9023. };
  9024. Engine.prototype.getAlphaTesting = function () {
  9025. return !!this._alphaTest;
  9026. };
  9027. // Textures
  9028. Engine.prototype.wipeCaches = function (bruteForce) {
  9029. if (this.preventCacheWipeBetweenFrames) {
  9030. return;
  9031. }
  9032. this.resetTextureCache();
  9033. this._currentEffect = null;
  9034. // 6/8/2017: deltakosh: Should not be required anymore.
  9035. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9036. if (bruteForce) {
  9037. this._stencilState.reset();
  9038. this._depthCullingState.reset();
  9039. this.setDepthFunctionToLessOrEqual();
  9040. this._alphaState.reset();
  9041. }
  9042. this._cachedVertexBuffers = null;
  9043. this._cachedIndexBuffer = null;
  9044. this._cachedEffectForVertexBuffers = null;
  9045. this._unBindVertexArrayObject();
  9046. this.bindIndexBuffer(null);
  9047. this.bindArrayBuffer(null);
  9048. };
  9049. /**
  9050. * Set the compressed texture format to use, based on the formats you have, and the formats
  9051. * supported by the hardware / browser.
  9052. *
  9053. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9054. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9055. * to API arguments needed to compressed textures. This puts the burden on the container
  9056. * generator to house the arcane code for determining these for current & future formats.
  9057. *
  9058. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9059. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9060. *
  9061. * Note: The result of this call is not taken into account when a texture is base64.
  9062. *
  9063. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9064. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9065. *
  9066. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9067. * @returns The extension selected.
  9068. */
  9069. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9070. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9071. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9072. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9073. return this._textureFormatInUse = this._texturesSupported[i];
  9074. }
  9075. }
  9076. }
  9077. // actively set format to nothing, to allow this to be called more than once
  9078. // and possibly fail the 2nd time
  9079. return this._textureFormatInUse = null;
  9080. };
  9081. /**
  9082. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9083. * @param {string} urlArg- This contains one of the following:
  9084. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9085. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9086. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9087. *
  9088. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9089. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9090. * @param {Scene} scene- Needed for loading to the correct scene.
  9091. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9092. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9093. * @param {callback} onError- Optional callback to be called upon failure.
  9094. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9095. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9096. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9097. *
  9098. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9099. */
  9100. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9101. var _this = this;
  9102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9103. if (onLoad === void 0) { onLoad = null; }
  9104. if (onError === void 0) { onError = null; }
  9105. if (buffer === void 0) { buffer = null; }
  9106. var texture = fallBack ? fallBack : this._gl.createTexture();
  9107. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9108. var fromData = url.substr(0, 5) === "data:";
  9109. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9110. // establish the file extension, if possible
  9111. var lastDot = url.lastIndexOf('.');
  9112. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9113. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9114. if (isDDS) {
  9115. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9116. }
  9117. var isTGA = (extension === ".tga");
  9118. // determine if a ktx file should be substituted
  9119. var isKTX = false;
  9120. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9121. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9122. isKTX = true;
  9123. }
  9124. scene._addPendingData(texture);
  9125. texture.url = url;
  9126. texture.noMipmap = noMipmap;
  9127. texture.references = 1;
  9128. texture.samplingMode = samplingMode;
  9129. texture.onLoadedCallbacks = [];
  9130. if (onLoad) {
  9131. texture.onLoadedCallbacks.push(onLoad);
  9132. }
  9133. if (!fallBack)
  9134. this._loadedTexturesCache.push(texture);
  9135. var onerror = function () {
  9136. scene._removePendingData(texture);
  9137. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9138. if (isKTX) {
  9139. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9140. }
  9141. else if (onError) {
  9142. onError();
  9143. }
  9144. };
  9145. var callback;
  9146. // processing for non-image formats
  9147. if (isKTX || isTGA || isDDS) {
  9148. if (isKTX) {
  9149. callback = function (data) {
  9150. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9151. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9152. ktx.uploadLevels(_this._gl, !noMipmap);
  9153. }, samplingMode);
  9154. };
  9155. }
  9156. else if (isTGA) {
  9157. callback = function (arrayBuffer) {
  9158. var data = new Uint8Array(arrayBuffer);
  9159. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9160. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9161. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9162. }, samplingMode);
  9163. };
  9164. }
  9165. else if (isDDS) {
  9166. callback = function (data) {
  9167. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9168. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9169. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9170. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9171. }, samplingMode);
  9172. };
  9173. }
  9174. if (!buffer) {
  9175. BABYLON.Tools.LoadFile(url, function (data) {
  9176. callback(data);
  9177. }, null, scene.database, true, onerror);
  9178. }
  9179. else {
  9180. callback(buffer);
  9181. }
  9182. // image format processing
  9183. }
  9184. else {
  9185. var onload = function (img) {
  9186. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9187. var isPot = (img.width === potWidth && img.height === potHeight);
  9188. if (!isPot) {
  9189. _this._prepareWorkingCanvas();
  9190. _this._workingCanvas.width = potWidth;
  9191. _this._workingCanvas.height = potHeight;
  9192. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9193. _this._workingContext.imageSmoothingEnabled = false;
  9194. _this._workingContext.mozImageSmoothingEnabled = false;
  9195. _this._workingContext.oImageSmoothingEnabled = false;
  9196. _this._workingContext.webkitImageSmoothingEnabled = false;
  9197. _this._workingContext.msImageSmoothingEnabled = false;
  9198. }
  9199. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9200. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9201. _this._workingContext.imageSmoothingEnabled = true;
  9202. _this._workingContext.mozImageSmoothingEnabled = true;
  9203. _this._workingContext.oImageSmoothingEnabled = true;
  9204. _this._workingContext.webkitImageSmoothingEnabled = true;
  9205. _this._workingContext.msImageSmoothingEnabled = true;
  9206. }
  9207. }
  9208. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9209. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9210. }, samplingMode);
  9211. };
  9212. if (!fromData || isBase64)
  9213. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9214. else if (buffer instanceof Array || typeof buffer === "string")
  9215. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9216. else
  9217. onload(buffer);
  9218. }
  9219. return texture;
  9220. };
  9221. Engine.prototype._getInternalFormat = function (format) {
  9222. var internalFormat = this._gl.RGBA;
  9223. switch (format) {
  9224. case Engine.TEXTUREFORMAT_ALPHA:
  9225. internalFormat = this._gl.ALPHA;
  9226. break;
  9227. case Engine.TEXTUREFORMAT_LUMINANCE:
  9228. internalFormat = this._gl.LUMINANCE;
  9229. break;
  9230. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9231. internalFormat = this._gl.LUMINANCE_ALPHA;
  9232. break;
  9233. case Engine.TEXTUREFORMAT_RGB:
  9234. internalFormat = this._gl.RGB;
  9235. break;
  9236. case Engine.TEXTUREFORMAT_RGBA:
  9237. internalFormat = this._gl.RGBA;
  9238. break;
  9239. }
  9240. return internalFormat;
  9241. };
  9242. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9243. if (compression === void 0) { compression = null; }
  9244. var internalFormat = this._getInternalFormat(format);
  9245. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9246. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9247. if (texture._width % 4 !== 0) {
  9248. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9249. }
  9250. if (compression) {
  9251. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9252. }
  9253. else {
  9254. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9255. }
  9256. if (texture.generateMipMaps) {
  9257. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9258. }
  9259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9260. this.resetTextureCache();
  9261. texture.isReady = true;
  9262. };
  9263. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9264. if (compression === void 0) { compression = null; }
  9265. var texture = this._gl.createTexture();
  9266. texture._baseWidth = width;
  9267. texture._baseHeight = height;
  9268. texture._width = width;
  9269. texture._height = height;
  9270. texture.references = 1;
  9271. this.updateRawTexture(texture, data, format, invertY, compression);
  9272. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9273. // Filters
  9274. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9275. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9276. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9277. if (generateMipMaps) {
  9278. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9279. }
  9280. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9281. texture.samplingMode = samplingMode;
  9282. this._loadedTexturesCache.push(texture);
  9283. return texture;
  9284. };
  9285. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9286. var texture = this._gl.createTexture();
  9287. texture._baseWidth = width;
  9288. texture._baseHeight = height;
  9289. if (generateMipMaps) {
  9290. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9291. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9292. }
  9293. this.resetTextureCache();
  9294. texture._width = width;
  9295. texture._height = height;
  9296. texture.isReady = false;
  9297. texture.generateMipMaps = generateMipMaps;
  9298. texture.references = 1;
  9299. texture.samplingMode = samplingMode;
  9300. this.updateTextureSamplingMode(samplingMode, texture);
  9301. this._loadedTexturesCache.push(texture);
  9302. return texture;
  9303. };
  9304. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9305. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9306. if (texture.isCube) {
  9307. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9308. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9309. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9310. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9311. }
  9312. else {
  9313. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9315. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9316. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9317. }
  9318. texture.samplingMode = samplingMode;
  9319. };
  9320. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9321. if (premulAlpha === void 0) { premulAlpha = false; }
  9322. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9323. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9324. if (premulAlpha) {
  9325. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9326. }
  9327. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9328. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9329. if (texture.generateMipMaps) {
  9330. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9331. }
  9332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9333. if (premulAlpha) {
  9334. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9335. }
  9336. this.resetTextureCache();
  9337. texture.isReady = true;
  9338. };
  9339. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9340. if (texture._isDisabled) {
  9341. return;
  9342. }
  9343. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9344. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9345. try {
  9346. // Testing video texture support
  9347. if (this._videoTextureSupported === undefined) {
  9348. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9349. if (this._gl.getError() !== 0) {
  9350. this._videoTextureSupported = false;
  9351. }
  9352. else {
  9353. this._videoTextureSupported = true;
  9354. }
  9355. }
  9356. // Copy video through the current working canvas if video texture is not supported
  9357. if (!this._videoTextureSupported) {
  9358. if (!texture._workingCanvas) {
  9359. texture._workingCanvas = document.createElement("canvas");
  9360. texture._workingContext = texture._workingCanvas.getContext("2d");
  9361. texture._workingCanvas.width = texture._width;
  9362. texture._workingCanvas.height = texture._height;
  9363. }
  9364. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9365. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9366. }
  9367. else {
  9368. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9369. }
  9370. if (texture.generateMipMaps) {
  9371. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9372. }
  9373. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9374. this.resetTextureCache();
  9375. texture.isReady = true;
  9376. }
  9377. catch (ex) {
  9378. // Something unexpected
  9379. // Let's disable the texture
  9380. texture._isDisabled = true;
  9381. }
  9382. };
  9383. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9384. // old version had a "generateMipMaps" arg instead of options.
  9385. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9386. // in the same way, generateDepthBuffer is defaulted to true
  9387. var generateMipMaps = false;
  9388. var generateDepthBuffer = true;
  9389. var generateStencilBuffer = false;
  9390. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9391. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9392. if (options !== undefined) {
  9393. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9394. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9395. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9396. type = options.type === undefined ? type : options.type;
  9397. if (options.samplingMode !== undefined) {
  9398. samplingMode = options.samplingMode;
  9399. }
  9400. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9401. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9402. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9403. }
  9404. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9405. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9406. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9407. }
  9408. }
  9409. var gl = this._gl;
  9410. var texture = gl.createTexture();
  9411. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9412. var width = size.width || size;
  9413. var height = size.height || size;
  9414. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9415. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9416. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9417. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9418. }
  9419. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9420. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9421. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9423. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9424. // Create the framebuffer
  9425. var framebuffer = gl.createFramebuffer();
  9426. this.bindUnboundFramebuffer(framebuffer);
  9427. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9428. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9429. if (generateMipMaps) {
  9430. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9431. }
  9432. // Unbind
  9433. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9434. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9435. this.bindUnboundFramebuffer(null);
  9436. texture._framebuffer = framebuffer;
  9437. texture._baseWidth = width;
  9438. texture._baseHeight = height;
  9439. texture._width = width;
  9440. texture._height = height;
  9441. texture.isReady = true;
  9442. texture.samples = 1;
  9443. texture.generateMipMaps = generateMipMaps;
  9444. texture.references = 1;
  9445. texture.samplingMode = samplingMode;
  9446. texture.type = type;
  9447. texture._generateDepthBuffer = generateDepthBuffer;
  9448. texture._generateStencilBuffer = generateStencilBuffer;
  9449. this.resetTextureCache();
  9450. this._loadedTexturesCache.push(texture);
  9451. return texture;
  9452. };
  9453. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9454. var generateMipMaps = false;
  9455. var generateDepthBuffer = true;
  9456. var generateStencilBuffer = false;
  9457. var generateDepthTexture = false;
  9458. var textureCount = 1;
  9459. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9460. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9461. var types = [], samplingModes = [];
  9462. if (options !== undefined) {
  9463. generateMipMaps = options.generateMipMaps;
  9464. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9465. generateStencilBuffer = options.generateStencilBuffer;
  9466. generateDepthTexture = options.generateDepthTexture;
  9467. textureCount = options.textureCount || 1;
  9468. if (options.types) {
  9469. types = options.types;
  9470. }
  9471. if (options.samplingModes) {
  9472. samplingModes = options.samplingModes;
  9473. }
  9474. }
  9475. var gl = this._gl;
  9476. // Create the framebuffer
  9477. var framebuffer = gl.createFramebuffer();
  9478. this.bindUnboundFramebuffer(framebuffer);
  9479. var width = size.width || size;
  9480. var height = size.height || size;
  9481. var textures = [];
  9482. var attachments = [];
  9483. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9484. for (var i = 0; i < textureCount; i++) {
  9485. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9486. var type = types[i] || defaultType;
  9487. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9488. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9490. }
  9491. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9492. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9493. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9494. }
  9495. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9496. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9497. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9498. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9499. }
  9500. var texture = gl.createTexture();
  9501. var attachment = gl["COLOR_ATTACHMENT" + i];
  9502. textures.push(texture);
  9503. attachments.push(attachment);
  9504. gl.activeTexture(gl["TEXTURE" + i]);
  9505. gl.bindTexture(gl.TEXTURE_2D, texture);
  9506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9510. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9511. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9512. if (generateMipMaps) {
  9513. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9514. }
  9515. // Unbind
  9516. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9517. texture._framebuffer = framebuffer;
  9518. texture._depthStencilBuffer = depthStencilBuffer;
  9519. texture._baseWidth = width;
  9520. texture._baseHeight = height;
  9521. texture._width = width;
  9522. texture._height = height;
  9523. texture.isReady = true;
  9524. texture.samples = 1;
  9525. texture.generateMipMaps = generateMipMaps;
  9526. texture.references = 1;
  9527. texture.samplingMode = samplingMode;
  9528. texture.type = type;
  9529. texture._generateDepthBuffer = generateDepthBuffer;
  9530. texture._generateStencilBuffer = generateStencilBuffer;
  9531. this._loadedTexturesCache.push(texture);
  9532. }
  9533. if (generateDepthTexture) {
  9534. // Depth texture
  9535. var depthTexture = gl.createTexture();
  9536. gl.activeTexture(gl.TEXTURE0);
  9537. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9538. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9539. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9540. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9541. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9542. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9543. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9544. depthTexture._framebuffer = framebuffer;
  9545. depthTexture._baseWidth = width;
  9546. depthTexture._baseHeight = height;
  9547. depthTexture._width = width;
  9548. depthTexture._height = height;
  9549. depthTexture.isReady = true;
  9550. depthTexture.samples = 1;
  9551. depthTexture.generateMipMaps = generateMipMaps;
  9552. depthTexture.references = 1;
  9553. depthTexture.samplingMode = gl.NEAREST;
  9554. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9555. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9556. textures.push(depthTexture);
  9557. this._loadedTexturesCache.push(depthTexture);
  9558. }
  9559. gl.drawBuffers(attachments);
  9560. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9561. this.bindUnboundFramebuffer(null);
  9562. this.resetTextureCache();
  9563. return textures;
  9564. };
  9565. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9566. if (samples === void 0) { samples = 1; }
  9567. var depthStencilBuffer = null;
  9568. var gl = this._gl;
  9569. // Create the depth/stencil buffer
  9570. if (generateStencilBuffer) {
  9571. depthStencilBuffer = gl.createRenderbuffer();
  9572. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9573. if (samples > 1) {
  9574. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9575. }
  9576. else {
  9577. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9578. }
  9579. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9580. }
  9581. else if (generateDepthBuffer) {
  9582. depthStencilBuffer = gl.createRenderbuffer();
  9583. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9584. if (samples > 1) {
  9585. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9586. }
  9587. else {
  9588. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9589. }
  9590. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9591. }
  9592. return depthStencilBuffer;
  9593. };
  9594. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9595. if (this.webGLVersion < 2) {
  9596. return 1;
  9597. }
  9598. if (texture.samples === samples) {
  9599. return samples;
  9600. }
  9601. var gl = this._gl;
  9602. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9603. // Dispose previous render buffers
  9604. if (texture._depthStencilBuffer) {
  9605. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9606. }
  9607. if (texture._MSAAFramebuffer) {
  9608. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9609. }
  9610. if (texture._MSAARenderBuffer) {
  9611. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9612. }
  9613. if (samples > 1) {
  9614. texture._MSAAFramebuffer = gl.createFramebuffer();
  9615. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9616. var colorRenderbuffer = gl.createRenderbuffer();
  9617. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9618. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9619. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9620. texture._MSAARenderBuffer = colorRenderbuffer;
  9621. }
  9622. else {
  9623. this.bindUnboundFramebuffer(texture._framebuffer);
  9624. }
  9625. texture.samples = samples;
  9626. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9627. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9628. this.bindUnboundFramebuffer(null);
  9629. return samples;
  9630. };
  9631. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9632. var gl = this._gl;
  9633. var texture = gl.createTexture();
  9634. var generateMipMaps = true;
  9635. var generateDepthBuffer = true;
  9636. var generateStencilBuffer = false;
  9637. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9638. if (options !== undefined) {
  9639. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9640. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9641. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9642. if (options.samplingMode !== undefined) {
  9643. samplingMode = options.samplingMode;
  9644. }
  9645. }
  9646. texture.isCube = true;
  9647. texture.references = 1;
  9648. texture.generateMipMaps = generateMipMaps;
  9649. texture.references = 1;
  9650. texture.samples = 1;
  9651. texture.samplingMode = samplingMode;
  9652. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9653. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9654. for (var face = 0; face < 6; face++) {
  9655. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9656. }
  9657. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9658. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9660. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9661. // Create the framebuffer
  9662. var framebuffer = gl.createFramebuffer();
  9663. this.bindUnboundFramebuffer(framebuffer);
  9664. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9665. // Mipmaps
  9666. if (texture.generateMipMaps) {
  9667. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9668. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9669. }
  9670. // Unbind
  9671. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9672. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9673. this.bindUnboundFramebuffer(null);
  9674. texture._framebuffer = framebuffer;
  9675. texture._width = size;
  9676. texture._height = size;
  9677. texture.isReady = true;
  9678. this.resetTextureCache();
  9679. this._loadedTexturesCache.push(texture);
  9680. return texture;
  9681. };
  9682. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9683. var _this = this;
  9684. if (onLoad === void 0) { onLoad = null; }
  9685. if (onError === void 0) { onError = null; }
  9686. var gl = this._gl;
  9687. var texture = gl.createTexture();
  9688. texture.isCube = true;
  9689. texture.url = rootUrl;
  9690. texture.references = 1;
  9691. texture.onLoadedCallbacks = [];
  9692. var isKTX = false;
  9693. var isDDS = false;
  9694. var lastDot = rootUrl.lastIndexOf('.');
  9695. var extension = rootUrl.substring(lastDot).toLowerCase();
  9696. if (this._textureFormatInUse) {
  9697. extension = this._textureFormatInUse;
  9698. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9699. isKTX = true;
  9700. }
  9701. else {
  9702. isDDS = (extension === ".dds");
  9703. }
  9704. if (isKTX) {
  9705. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9706. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9707. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9708. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9709. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9710. ktx.uploadLevels(_this._gl, !noMipmap);
  9711. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9713. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9714. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9715. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9716. _this.resetTextureCache();
  9717. texture._width = ktx.pixelWidth;
  9718. texture._height = ktx.pixelHeight;
  9719. texture.isReady = true;
  9720. }, null, null, true, onError);
  9721. }
  9722. else if (isDDS) {
  9723. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9724. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9725. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9726. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9727. if (info.isCompressed) {
  9728. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9729. }
  9730. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  9731. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9732. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9733. }
  9734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9737. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9738. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9739. _this.resetTextureCache();
  9740. texture._width = info.width;
  9741. texture._height = info.height;
  9742. texture.isReady = true;
  9743. texture.type = info.textureType;
  9744. }, null, null, true, onError);
  9745. }
  9746. else {
  9747. cascadeLoad(rootUrl, scene, function (imgs) {
  9748. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9749. var height = width;
  9750. _this._prepareWorkingCanvas();
  9751. _this._workingCanvas.width = width;
  9752. _this._workingCanvas.height = height;
  9753. var faces = [
  9754. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9755. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9756. ];
  9757. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9758. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9759. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9760. for (var index = 0; index < faces.length; index++) {
  9761. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9762. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9763. }
  9764. if (!noMipmap) {
  9765. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9766. }
  9767. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9768. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9769. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9771. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9772. _this.resetTextureCache();
  9773. texture._width = width;
  9774. texture._height = height;
  9775. texture.isReady = true;
  9776. texture.onLoadedCallbacks.forEach(function (callback) {
  9777. callback();
  9778. });
  9779. if (onLoad) {
  9780. onLoad();
  9781. }
  9782. }, files, onError);
  9783. }
  9784. this._loadedTexturesCache.push(texture);
  9785. return texture;
  9786. };
  9787. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9788. texture._width = width;
  9789. texture._height = height;
  9790. texture._size = width * height;
  9791. texture._baseWidth = width;
  9792. texture._baseHeight = height;
  9793. };
  9794. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9795. if (compression === void 0) { compression = null; }
  9796. if (level === void 0) { level = 0; }
  9797. var gl = this._gl;
  9798. var textureType = this._getWebGLTextureType(type);
  9799. var internalFormat = this._getInternalFormat(format);
  9800. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9801. var needConversion = false;
  9802. if (internalFormat === gl.RGB) {
  9803. internalFormat = gl.RGBA;
  9804. needConversion = true;
  9805. }
  9806. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9807. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9808. if (texture._width % 4 !== 0) {
  9809. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9810. }
  9811. var facesIndex = [
  9812. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9813. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9814. ];
  9815. // Data are known to be in +X +Y +Z -X -Y -Z
  9816. for (var index = 0; index < facesIndex.length; index++) {
  9817. var faceData = data[index];
  9818. if (compression) {
  9819. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9820. }
  9821. else {
  9822. if (needConversion) {
  9823. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9824. }
  9825. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9826. }
  9827. }
  9828. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9829. if (isPot && texture.generateMipMaps && level === 0) {
  9830. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9831. }
  9832. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9833. this.resetTextureCache();
  9834. texture.isReady = true;
  9835. };
  9836. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9837. if (compression === void 0) { compression = null; }
  9838. var gl = this._gl;
  9839. var texture = gl.createTexture();
  9840. texture.isCube = true;
  9841. texture.references = 1;
  9842. var textureType = this._getWebGLTextureType(type);
  9843. var internalFormat = this._getInternalFormat(format);
  9844. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9845. var needConversion = false;
  9846. if (internalFormat === gl.RGB) {
  9847. internalFormat = gl.RGBA;
  9848. needConversion = true;
  9849. }
  9850. var width = size;
  9851. var height = width;
  9852. texture._width = width;
  9853. texture._height = height;
  9854. // Double check on POT to generate Mips.
  9855. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9856. if (!isPot) {
  9857. generateMipMaps = false;
  9858. }
  9859. texture.generateMipMaps = generateMipMaps;
  9860. // Upload data if needed. The texture won t be ready until then.
  9861. if (data) {
  9862. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9863. }
  9864. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9865. // Filters
  9866. if (data && generateMipMaps) {
  9867. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9868. }
  9869. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9870. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9871. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9872. }
  9873. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9876. }
  9877. else {
  9878. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9881. }
  9882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9884. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9885. this._loadedTexturesCache.push(texture);
  9886. return texture;
  9887. };
  9888. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9889. var _this = this;
  9890. if (onLoad === void 0) { onLoad = null; }
  9891. if (onError === void 0) { onError = null; }
  9892. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9893. if (invertY === void 0) { invertY = false; }
  9894. var gl = this._gl;
  9895. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9896. scene._addPendingData(texture);
  9897. texture.url = url;
  9898. var onerror = function () {
  9899. scene._removePendingData(texture);
  9900. if (onError) {
  9901. onError();
  9902. }
  9903. };
  9904. var internalCallback = function (data) {
  9905. var rgbeDataArrays = callback(data);
  9906. var facesIndex = [
  9907. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9908. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9909. ];
  9910. var width = texture._width;
  9911. var height = texture._height;
  9912. if (mipmmapGenerator) {
  9913. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9914. // I ll remove ASAP.
  9915. var textureType = _this._getWebGLTextureType(type);
  9916. var internalFormat = _this._getInternalFormat(format);
  9917. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9918. var needConversion = false;
  9919. if (internalFormat === gl.RGB) {
  9920. internalFormat = gl.RGBA;
  9921. needConversion = true;
  9922. }
  9923. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9924. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9925. var arrayTemp = [];
  9926. // Data are known to be in +X +Y +Z -X -Y -Z
  9927. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9928. arrayTemp.push(rgbeDataArrays[0]); // +X
  9929. arrayTemp.push(rgbeDataArrays[3]); // -X
  9930. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9931. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9932. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9933. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9934. var mipData = mipmmapGenerator(arrayTemp);
  9935. // mipData is order in +X -X +Y -Y +Z -Z
  9936. var mipFaces = [0, 2, 4, 1, 3, 5];
  9937. for (var level = 0; level < mipData.length; level++) {
  9938. var mipSize = width >> level;
  9939. for (var mipIndex in mipFaces) {
  9940. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9941. if (needConversion) {
  9942. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9943. }
  9944. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9945. }
  9946. }
  9947. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9948. }
  9949. else {
  9950. texture.generateMipMaps = !noMipmap;
  9951. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9952. }
  9953. texture.isReady = true;
  9954. _this.resetTextureCache();
  9955. scene._removePendingData(texture);
  9956. if (onLoad) {
  9957. onLoad();
  9958. }
  9959. };
  9960. BABYLON.Tools.LoadFile(url, function (data) {
  9961. internalCallback(data);
  9962. }, onerror, scene.database, true);
  9963. return texture;
  9964. };
  9965. ;
  9966. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9967. // Create new RGBA data container.
  9968. var rgbaData;
  9969. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9970. rgbaData = new Float32Array(width * height * 4);
  9971. }
  9972. else {
  9973. rgbaData = new Uint32Array(width * height * 4);
  9974. }
  9975. // Convert each pixel.
  9976. for (var x = 0; x < width; x++) {
  9977. for (var y = 0; y < height; y++) {
  9978. var index = (y * width + x) * 3;
  9979. var newIndex = (y * width + x) * 4;
  9980. // Map Old Value to new value.
  9981. rgbaData[newIndex + 0] = rgbData[index + 0];
  9982. rgbaData[newIndex + 1] = rgbData[index + 1];
  9983. rgbaData[newIndex + 2] = rgbData[index + 2];
  9984. // Add fully opaque alpha channel.
  9985. rgbaData[newIndex + 3] = 1;
  9986. }
  9987. }
  9988. return rgbaData;
  9989. };
  9990. Engine.prototype._releaseFramebufferObjects = function (texture) {
  9991. var gl = this._gl;
  9992. if (texture._framebuffer) {
  9993. gl.deleteFramebuffer(texture._framebuffer);
  9994. texture._framebuffer = null;
  9995. }
  9996. if (texture._depthStencilBuffer) {
  9997. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9998. texture._depthStencilBuffer = null;
  9999. }
  10000. if (texture._MSAAFramebuffer) {
  10001. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10002. texture._MSAAFramebuffer = null;
  10003. }
  10004. if (texture._MSAARenderBuffer) {
  10005. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10006. texture._MSAARenderBuffer = null;
  10007. }
  10008. };
  10009. Engine.prototype._releaseTexture = function (texture) {
  10010. var gl = this._gl;
  10011. this._releaseFramebufferObjects(texture);
  10012. gl.deleteTexture(texture);
  10013. // Unbind channels
  10014. this.unbindAllTextures();
  10015. var index = this._loadedTexturesCache.indexOf(texture);
  10016. if (index !== -1) {
  10017. this._loadedTexturesCache.splice(index, 1);
  10018. }
  10019. };
  10020. Engine.prototype.setProgram = function (program) {
  10021. if (this._currentProgram !== program) {
  10022. this._gl.useProgram(program);
  10023. this._currentProgram = program;
  10024. }
  10025. };
  10026. Engine.prototype.bindSamplers = function (effect) {
  10027. this.setProgram(effect.getProgram());
  10028. var samplers = effect.getSamplers();
  10029. for (var index = 0; index < samplers.length; index++) {
  10030. var uniform = effect.getUniform(samplers[index]);
  10031. this._gl.uniform1i(uniform, index);
  10032. }
  10033. this._currentEffect = null;
  10034. };
  10035. Engine.prototype.activateTexture = function (texture) {
  10036. if (this._activeTexture !== texture) {
  10037. this._gl.activeTexture(texture);
  10038. this._activeTexture = texture;
  10039. }
  10040. };
  10041. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10042. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10043. this._gl.bindTexture(target, texture);
  10044. this._activeTexturesCache[this._activeTexture] = texture;
  10045. }
  10046. };
  10047. Engine.prototype._bindTexture = function (channel, texture) {
  10048. if (channel < 0) {
  10049. return;
  10050. }
  10051. this.activateTexture(this._gl.TEXTURE0 + channel);
  10052. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10053. };
  10054. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10055. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10056. };
  10057. Engine.prototype.unbindAllTextures = function () {
  10058. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10059. this.activateTexture(this._gl["TEXTURE" + channel]);
  10060. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10061. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10062. }
  10063. };
  10064. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10065. if (channel < 0) {
  10066. return;
  10067. }
  10068. this._gl.uniform1i(uniform, channel);
  10069. this._setTexture(channel, texture);
  10070. };
  10071. Engine.prototype._setTexture = function (channel, texture) {
  10072. // Not ready?
  10073. if (!texture) {
  10074. if (this._activeTexturesCache[channel] != null) {
  10075. this.activateTexture(this._gl["TEXTURE" + channel]);
  10076. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10077. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10078. }
  10079. return;
  10080. }
  10081. // Video
  10082. var alreadyActivated = false;
  10083. if (texture.video) {
  10084. this.activateTexture(this._gl["TEXTURE" + channel]);
  10085. alreadyActivated = true;
  10086. texture.update();
  10087. }
  10088. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10089. texture.delayLoad();
  10090. return;
  10091. }
  10092. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10093. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10094. if (this._activeTexturesCache[channel] === internalTexture) {
  10095. return;
  10096. }
  10097. if (!alreadyActivated) {
  10098. this.activateTexture(this._gl["TEXTURE" + channel]);
  10099. }
  10100. if (internalTexture.isCube) {
  10101. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10102. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10103. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10104. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10105. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10106. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10107. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10108. }
  10109. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10110. }
  10111. else {
  10112. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10113. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10114. internalTexture._cachedWrapU = texture.wrapU;
  10115. switch (texture.wrapU) {
  10116. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10117. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10118. break;
  10119. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10120. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10121. break;
  10122. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10123. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10124. break;
  10125. }
  10126. }
  10127. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10128. internalTexture._cachedWrapV = texture.wrapV;
  10129. switch (texture.wrapV) {
  10130. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10131. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10132. break;
  10133. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10134. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10135. break;
  10136. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10137. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10138. break;
  10139. }
  10140. }
  10141. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10142. }
  10143. };
  10144. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10145. if (channel < 0) {
  10146. return;
  10147. }
  10148. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10149. this._textureUnits = new Int32Array(textures.length);
  10150. }
  10151. for (var i = 0; i < textures.length; i++) {
  10152. this._textureUnits[i] = channel + i;
  10153. }
  10154. this._gl.uniform1iv(uniform, this._textureUnits);
  10155. for (var index = 0; index < textures.length; index++) {
  10156. this._setTexture(channel + index, textures[index]);
  10157. }
  10158. };
  10159. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10160. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10161. var value = texture.anisotropicFilteringLevel;
  10162. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10163. value = 1;
  10164. }
  10165. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10166. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10167. texture._cachedAnisotropicFilteringLevel = value;
  10168. }
  10169. };
  10170. Engine.prototype.readPixels = function (x, y, width, height) {
  10171. var data = new Uint8Array(height * width * 4);
  10172. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10173. return data;
  10174. };
  10175. /**
  10176. * Add an externaly attached data from its key.
  10177. * This method call will fail and return false, if such key already exists.
  10178. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10179. * @param key the unique key that identifies the data
  10180. * @param data the data object to associate to the key for this Engine instance
  10181. * @return true if no such key were already present and the data was added successfully, false otherwise
  10182. */
  10183. Engine.prototype.addExternalData = function (key, data) {
  10184. if (!this._externalData) {
  10185. this._externalData = new BABYLON.StringDictionary();
  10186. }
  10187. return this._externalData.add(key, data);
  10188. };
  10189. /**
  10190. * Get an externaly attached data from its key
  10191. * @param key the unique key that identifies the data
  10192. * @return the associated data, if present (can be null), or undefined if not present
  10193. */
  10194. Engine.prototype.getExternalData = function (key) {
  10195. if (!this._externalData) {
  10196. this._externalData = new BABYLON.StringDictionary();
  10197. }
  10198. return this._externalData.get(key);
  10199. };
  10200. /**
  10201. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10202. * @param key the unique key that identifies the data
  10203. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10204. * @return the associated data, can be null if the factory returned null.
  10205. */
  10206. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10207. if (!this._externalData) {
  10208. this._externalData = new BABYLON.StringDictionary();
  10209. }
  10210. return this._externalData.getOrAddWithFactory(key, factory);
  10211. };
  10212. /**
  10213. * Remove an externaly attached data from the Engine instance
  10214. * @param key the unique key that identifies the data
  10215. * @return true if the data was successfully removed, false if it doesn't exist
  10216. */
  10217. Engine.prototype.removeExternalData = function (key) {
  10218. if (!this._externalData) {
  10219. this._externalData = new BABYLON.StringDictionary();
  10220. }
  10221. return this._externalData.remove(key);
  10222. };
  10223. Engine.prototype.releaseInternalTexture = function (texture) {
  10224. if (!texture) {
  10225. return;
  10226. }
  10227. texture.references--;
  10228. // Final reference ?
  10229. if (texture.references === 0) {
  10230. var texturesCache = this.getLoadedTexturesCache();
  10231. var index = texturesCache.indexOf(texture);
  10232. if (index > -1) {
  10233. texturesCache.splice(index, 1);
  10234. }
  10235. this._releaseTexture(texture);
  10236. }
  10237. };
  10238. Engine.prototype.unbindAllAttributes = function () {
  10239. if (this._mustWipeVertexAttributes) {
  10240. this._mustWipeVertexAttributes = false;
  10241. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10242. this._gl.disableVertexAttribArray(i);
  10243. this._vertexAttribArraysEnabled[i] = false;
  10244. this._currentBufferPointers[i] = null;
  10245. }
  10246. return;
  10247. }
  10248. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10249. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10250. continue;
  10251. }
  10252. this._gl.disableVertexAttribArray(i);
  10253. this._vertexAttribArraysEnabled[i] = false;
  10254. this._currentBufferPointers[i] = null;
  10255. }
  10256. };
  10257. Engine.prototype.releaseEffects = function () {
  10258. for (var name in this._compiledEffects) {
  10259. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10260. }
  10261. this._compiledEffects = {};
  10262. };
  10263. // Dispose
  10264. Engine.prototype.dispose = function () {
  10265. this.hideLoadingUI();
  10266. this.stopRenderLoop();
  10267. // Empty texture
  10268. if (this._emptyTexture) {
  10269. this._releaseTexture(this._emptyTexture);
  10270. this._emptyTexture = null;
  10271. }
  10272. if (this._emptyCubeTexture) {
  10273. this._releaseTexture(this._emptyCubeTexture);
  10274. this._emptyCubeTexture = null;
  10275. }
  10276. // Release scenes
  10277. while (this.scenes.length) {
  10278. this.scenes[0].dispose();
  10279. }
  10280. // Release audio engine
  10281. if (Engine.audioEngine) {
  10282. Engine.audioEngine.dispose();
  10283. }
  10284. // Release effects
  10285. this.releaseEffects();
  10286. // Unbind
  10287. this.unbindAllAttributes();
  10288. if (this._dummyFramebuffer) {
  10289. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10290. }
  10291. this._gl = null;
  10292. //WebVR
  10293. this.disableVR();
  10294. // Events
  10295. window.removeEventListener("blur", this._onBlur);
  10296. window.removeEventListener("focus", this._onFocus);
  10297. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10298. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10299. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10300. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10301. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10302. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10303. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10304. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10305. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10306. // Remove from Instances
  10307. var index = Engine.Instances.indexOf(this);
  10308. if (index >= 0) {
  10309. Engine.Instances.splice(index, 1);
  10310. }
  10311. };
  10312. // Loading screen
  10313. Engine.prototype.displayLoadingUI = function () {
  10314. var loadingScreen = this.loadingScreen;
  10315. if (loadingScreen) {
  10316. loadingScreen.displayLoadingUI();
  10317. }
  10318. };
  10319. Engine.prototype.hideLoadingUI = function () {
  10320. var loadingScreen = this.loadingScreen;
  10321. if (loadingScreen) {
  10322. loadingScreen.hideLoadingUI();
  10323. }
  10324. };
  10325. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10326. get: function () {
  10327. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10328. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10329. return this._loadingScreen;
  10330. },
  10331. set: function (loadingScreen) {
  10332. this._loadingScreen = loadingScreen;
  10333. },
  10334. enumerable: true,
  10335. configurable: true
  10336. });
  10337. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10338. set: function (text) {
  10339. this.loadingScreen.loadingUIText = text;
  10340. },
  10341. enumerable: true,
  10342. configurable: true
  10343. });
  10344. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10345. set: function (color) {
  10346. this.loadingScreen.loadingUIBackgroundColor = color;
  10347. },
  10348. enumerable: true,
  10349. configurable: true
  10350. });
  10351. Engine.prototype.attachContextLostEvent = function (callback) {
  10352. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10353. };
  10354. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10355. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10356. };
  10357. Engine.prototype.getVertexShaderSource = function (program) {
  10358. var shaders = this._gl.getAttachedShaders(program);
  10359. return this._gl.getShaderSource(shaders[0]);
  10360. };
  10361. Engine.prototype.getFragmentShaderSource = function (program) {
  10362. var shaders = this._gl.getAttachedShaders(program);
  10363. return this._gl.getShaderSource(shaders[1]);
  10364. };
  10365. Engine.prototype.getError = function () {
  10366. return this._gl.getError();
  10367. };
  10368. // FPS
  10369. Engine.prototype.getFps = function () {
  10370. return this.fps;
  10371. };
  10372. Engine.prototype.getDeltaTime = function () {
  10373. return this.deltaTime;
  10374. };
  10375. Engine.prototype._measureFps = function () {
  10376. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10377. var length = this.previousFramesDuration.length;
  10378. if (length >= 2) {
  10379. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10380. }
  10381. if (length >= this.fpsRange) {
  10382. if (length > this.fpsRange) {
  10383. this.previousFramesDuration.splice(0, 1);
  10384. length = this.previousFramesDuration.length;
  10385. }
  10386. var sum = 0;
  10387. for (var id = 0; id < length - 1; id++) {
  10388. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10389. }
  10390. this.fps = 1000.0 / (sum / (length - 1));
  10391. }
  10392. };
  10393. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, lodIndex) {
  10394. if (faceIndex === void 0) { faceIndex = -1; }
  10395. if (lodIndex === void 0) { lodIndex = 0; }
  10396. var gl = this._gl;
  10397. if (!this._dummyFramebuffer) {
  10398. this._dummyFramebuffer = gl.createFramebuffer();
  10399. }
  10400. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10401. if (faceIndex > -1) {
  10402. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, lodIndex);
  10403. }
  10404. else {
  10405. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, lodIndex);
  10406. }
  10407. var readFormat = gl.RGBA;
  10408. var readType = (texture.type !== undefined) ? texture.type : gl.UNSIGNED_BYTE;
  10409. var buffer = new Uint8Array(4 * width * height);
  10410. gl.readPixels(0, 0, width, height, readFormat, readType, buffer);
  10411. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10412. return buffer;
  10413. };
  10414. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10415. if (this._webGLVersion > 1) {
  10416. return this._caps.colorBufferFloat;
  10417. }
  10418. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10419. };
  10420. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10421. if (this._webGLVersion > 1) {
  10422. return this._caps.colorBufferFloat;
  10423. }
  10424. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10425. };
  10426. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10427. Engine.prototype._canRenderToFramebuffer = function (type) {
  10428. var gl = this._gl;
  10429. //clear existing errors
  10430. while (gl.getError() !== gl.NO_ERROR) { }
  10431. var successful = true;
  10432. var texture = gl.createTexture();
  10433. gl.bindTexture(gl.TEXTURE_2D, texture);
  10434. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10437. var fb = gl.createFramebuffer();
  10438. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10439. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10440. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10441. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10442. successful = successful && (gl.getError() === gl.NO_ERROR);
  10443. //try render by clearing frame buffer's color buffer
  10444. if (successful) {
  10445. gl.clear(gl.COLOR_BUFFER_BIT);
  10446. successful = successful && (gl.getError() === gl.NO_ERROR);
  10447. }
  10448. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10449. if (successful) {
  10450. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10451. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10452. var readFormat = gl.RGBA;
  10453. var readType = gl.UNSIGNED_BYTE;
  10454. var buffer = new Uint8Array(4);
  10455. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10456. successful = successful && (gl.getError() === gl.NO_ERROR);
  10457. }
  10458. //clean up
  10459. gl.deleteTexture(texture);
  10460. gl.deleteFramebuffer(fb);
  10461. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10462. //clear accumulated errors
  10463. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10464. return successful;
  10465. };
  10466. Engine.prototype._getWebGLTextureType = function (type) {
  10467. if (type === Engine.TEXTURETYPE_FLOAT) {
  10468. return this._gl.FLOAT;
  10469. }
  10470. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10471. // Add Half Float Constant.
  10472. return this._gl.HALF_FLOAT_OES;
  10473. }
  10474. return this._gl.UNSIGNED_BYTE;
  10475. };
  10476. ;
  10477. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10478. if (this._webGLVersion === 1) {
  10479. return this._gl.RGBA;
  10480. }
  10481. if (type === Engine.TEXTURETYPE_FLOAT) {
  10482. return this._gl.RGBA32F;
  10483. }
  10484. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10485. return this._gl.RGBA16F;
  10486. }
  10487. return this._gl.RGBA;
  10488. };
  10489. ;
  10490. // Statics
  10491. Engine.isSupported = function () {
  10492. try {
  10493. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10494. if (navigator.isCocoonJS) {
  10495. return true;
  10496. }
  10497. var tempcanvas = document.createElement("canvas");
  10498. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10499. return gl != null && !!window.WebGLRenderingContext;
  10500. }
  10501. catch (e) {
  10502. return false;
  10503. }
  10504. };
  10505. return Engine;
  10506. }());
  10507. Engine.Instances = new Array();
  10508. // Const statics
  10509. Engine._ALPHA_DISABLE = 0;
  10510. Engine._ALPHA_ADD = 1;
  10511. Engine._ALPHA_COMBINE = 2;
  10512. Engine._ALPHA_SUBTRACT = 3;
  10513. Engine._ALPHA_MULTIPLY = 4;
  10514. Engine._ALPHA_MAXIMIZED = 5;
  10515. Engine._ALPHA_ONEONE = 6;
  10516. Engine._ALPHA_PREMULTIPLIED = 7;
  10517. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10518. Engine._ALPHA_INTERPOLATE = 9;
  10519. Engine._ALPHA_SCREENMODE = 10;
  10520. Engine._DELAYLOADSTATE_NONE = 0;
  10521. Engine._DELAYLOADSTATE_LOADED = 1;
  10522. Engine._DELAYLOADSTATE_LOADING = 2;
  10523. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10524. Engine._TEXTUREFORMAT_ALPHA = 0;
  10525. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10526. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10527. Engine._TEXTUREFORMAT_RGB = 4;
  10528. Engine._TEXTUREFORMAT_RGBA = 5;
  10529. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10530. Engine._TEXTURETYPE_FLOAT = 1;
  10531. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10532. // Depht or Stencil test Constants.
  10533. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10534. 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.
  10535. 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.
  10536. 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.
  10537. 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.
  10538. 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.
  10539. 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.
  10540. 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.
  10541. // Stencil Actions Constants.
  10542. Engine._KEEP = 0x1E00;
  10543. Engine._REPLACE = 0x1E01;
  10544. Engine._INCR = 0x1E02;
  10545. Engine._DECR = 0x1E03;
  10546. Engine._INVERT = 0x150A;
  10547. Engine._INCR_WRAP = 0x8507;
  10548. Engine._DECR_WRAP = 0x8508;
  10549. // Texture rescaling mode
  10550. Engine._SCALEMODE_FLOOR = 1;
  10551. Engine._SCALEMODE_NEAREST = 2;
  10552. Engine._SCALEMODE_CEILING = 3;
  10553. // Updatable statics so stick with vars here
  10554. Engine.CollisionsEpsilon = 0.001;
  10555. Engine.CodeRepository = "src/";
  10556. Engine.ShadersRepository = "src/Shaders/";
  10557. BABYLON.Engine = Engine;
  10558. })(BABYLON || (BABYLON = {}));
  10559. //# sourceMappingURL=babylon.engine.js.map
  10560. /// <reference path="Tools\babylon.decorators.ts" />
  10561. var BABYLON;
  10562. (function (BABYLON) {
  10563. /**
  10564. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10565. */
  10566. var Node = (function () {
  10567. /**
  10568. * @constructor
  10569. * @param {string} name - the name and id to be given to this node
  10570. * @param {BABYLON.Scene} the scene this node will be added to
  10571. */
  10572. function Node(name, scene) {
  10573. this.state = "";
  10574. this.metadata = null;
  10575. this.doNotSerialize = false;
  10576. this.animations = new Array();
  10577. this._ranges = {};
  10578. this._childrenFlag = -1;
  10579. this._isEnabled = true;
  10580. this._isReady = true;
  10581. this._currentRenderId = -1;
  10582. this._parentRenderId = -1;
  10583. /**
  10584. * An event triggered when the mesh is disposed.
  10585. * @type {BABYLON.Observable}
  10586. */
  10587. this.onDisposeObservable = new BABYLON.Observable();
  10588. this.name = name;
  10589. this.id = name;
  10590. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10591. this._initCache();
  10592. }
  10593. Object.defineProperty(Node.prototype, "parent", {
  10594. get: function () {
  10595. return this._parentNode;
  10596. },
  10597. set: function (parent) {
  10598. if (this._parentNode === parent) {
  10599. return;
  10600. }
  10601. if (this._parentNode) {
  10602. var index = this._parentNode._children.indexOf(this);
  10603. if (index !== -1) {
  10604. this._parentNode._children.splice(index, 1);
  10605. }
  10606. }
  10607. this._parentNode = parent;
  10608. if (this._parentNode) {
  10609. if (!this._parentNode._children) {
  10610. this._parentNode._children = new Array();
  10611. }
  10612. this._parentNode._children.push(this);
  10613. }
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. Node.prototype.getClassName = function () {
  10619. return "Node";
  10620. };
  10621. Object.defineProperty(Node.prototype, "onDispose", {
  10622. set: function (callback) {
  10623. if (this._onDisposeObserver) {
  10624. this.onDisposeObservable.remove(this._onDisposeObserver);
  10625. }
  10626. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10627. },
  10628. enumerable: true,
  10629. configurable: true
  10630. });
  10631. Node.prototype.getScene = function () {
  10632. return this._scene;
  10633. };
  10634. Node.prototype.getEngine = function () {
  10635. return this._scene.getEngine();
  10636. };
  10637. // override it in derived class
  10638. Node.prototype.getWorldMatrix = function () {
  10639. return BABYLON.Matrix.Identity();
  10640. };
  10641. // override it in derived class if you add new variables to the cache
  10642. // and call the parent class method
  10643. Node.prototype._initCache = function () {
  10644. this._cache = {};
  10645. this._cache.parent = undefined;
  10646. };
  10647. Node.prototype.updateCache = function (force) {
  10648. if (!force && this.isSynchronized())
  10649. return;
  10650. this._cache.parent = this.parent;
  10651. this._updateCache();
  10652. };
  10653. // override it in derived class if you add new variables to the cache
  10654. // and call the parent class method if !ignoreParentClass
  10655. Node.prototype._updateCache = function (ignoreParentClass) {
  10656. };
  10657. // override it in derived class if you add new variables to the cache
  10658. Node.prototype._isSynchronized = function () {
  10659. return true;
  10660. };
  10661. Node.prototype._markSyncedWithParent = function () {
  10662. this._parentRenderId = this.parent._currentRenderId;
  10663. };
  10664. Node.prototype.isSynchronizedWithParent = function () {
  10665. if (!this.parent) {
  10666. return true;
  10667. }
  10668. if (this._parentRenderId !== this.parent._currentRenderId) {
  10669. return false;
  10670. }
  10671. return this.parent.isSynchronized();
  10672. };
  10673. Node.prototype.isSynchronized = function (updateCache) {
  10674. var check = this.hasNewParent();
  10675. check = check || !this.isSynchronizedWithParent();
  10676. check = check || !this._isSynchronized();
  10677. if (updateCache)
  10678. this.updateCache(true);
  10679. return !check;
  10680. };
  10681. Node.prototype.hasNewParent = function (update) {
  10682. if (this._cache.parent === this.parent)
  10683. return false;
  10684. if (update)
  10685. this._cache.parent = this.parent;
  10686. return true;
  10687. };
  10688. /**
  10689. * Is this node ready to be used/rendered
  10690. * @return {boolean} is it ready
  10691. */
  10692. Node.prototype.isReady = function () {
  10693. return this._isReady;
  10694. };
  10695. /**
  10696. * Is this node enabled.
  10697. * If the node has a parent and is enabled, the parent will be inspected as well.
  10698. * @return {boolean} whether this node (and its parent) is enabled.
  10699. * @see setEnabled
  10700. */
  10701. Node.prototype.isEnabled = function () {
  10702. if (!this._isEnabled) {
  10703. return false;
  10704. }
  10705. if (this.parent) {
  10706. return this.parent.isEnabled();
  10707. }
  10708. return true;
  10709. };
  10710. /**
  10711. * Set the enabled state of this node.
  10712. * @param {boolean} value - the new enabled state
  10713. * @see isEnabled
  10714. */
  10715. Node.prototype.setEnabled = function (value) {
  10716. this._isEnabled = value;
  10717. };
  10718. /**
  10719. * Is this node a descendant of the given node.
  10720. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10721. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10722. * @see parent
  10723. */
  10724. Node.prototype.isDescendantOf = function (ancestor) {
  10725. if (this.parent) {
  10726. if (this.parent === ancestor) {
  10727. return true;
  10728. }
  10729. return this.parent.isDescendantOf(ancestor);
  10730. }
  10731. return false;
  10732. };
  10733. /**
  10734. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10735. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10736. * @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.
  10737. * @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.
  10738. */
  10739. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10740. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10741. if (!this._children) {
  10742. return;
  10743. }
  10744. for (var index = 0; index < this._children.length; index++) {
  10745. var item = this._children[index];
  10746. if (!predicate || predicate(item)) {
  10747. results.push(item);
  10748. }
  10749. if (!directDescendantsOnly) {
  10750. item._getDescendants(results, false, predicate);
  10751. }
  10752. }
  10753. };
  10754. /**
  10755. * Will return all nodes that have this node as ascendant.
  10756. * @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.
  10757. * @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.
  10758. * @return {BABYLON.Node[]} all children nodes of all types.
  10759. */
  10760. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10761. var results = [];
  10762. this._getDescendants(results, directDescendantsOnly, predicate);
  10763. return results;
  10764. };
  10765. /**
  10766. * Get all child-meshes of this node.
  10767. */
  10768. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10769. var results = [];
  10770. this._getDescendants(results, directDecendantsOnly, function (node) {
  10771. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10772. });
  10773. return results;
  10774. };
  10775. /**
  10776. * Get all direct children of this node.
  10777. */
  10778. Node.prototype.getChildren = function (predicate) {
  10779. return this.getDescendants(true, predicate);
  10780. };
  10781. Node.prototype._setReady = function (state) {
  10782. if (state === this._isReady) {
  10783. return;
  10784. }
  10785. if (!state) {
  10786. this._isReady = false;
  10787. return;
  10788. }
  10789. this._isReady = true;
  10790. if (this.onReady) {
  10791. this.onReady(this);
  10792. }
  10793. };
  10794. Node.prototype.getAnimationByName = function (name) {
  10795. for (var i = 0; i < this.animations.length; i++) {
  10796. var animation = this.animations[i];
  10797. if (animation.name === name) {
  10798. return animation;
  10799. }
  10800. }
  10801. return null;
  10802. };
  10803. Node.prototype.createAnimationRange = function (name, from, to) {
  10804. // check name not already in use
  10805. if (!this._ranges[name]) {
  10806. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10807. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10808. if (this.animations[i]) {
  10809. this.animations[i].createRange(name, from, to);
  10810. }
  10811. }
  10812. }
  10813. };
  10814. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10815. if (deleteFrames === void 0) { deleteFrames = true; }
  10816. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10817. if (this.animations[i]) {
  10818. this.animations[i].deleteRange(name, deleteFrames);
  10819. }
  10820. }
  10821. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10822. };
  10823. Node.prototype.getAnimationRange = function (name) {
  10824. return this._ranges[name];
  10825. };
  10826. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10827. var range = this.getAnimationRange(name);
  10828. if (!range) {
  10829. return null;
  10830. }
  10831. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10832. };
  10833. Node.prototype.serializeAnimationRanges = function () {
  10834. var serializationRanges = [];
  10835. for (var name in this._ranges) {
  10836. var range = {};
  10837. range.name = name;
  10838. range.from = this._ranges[name].from;
  10839. range.to = this._ranges[name].to;
  10840. serializationRanges.push(range);
  10841. }
  10842. return serializationRanges;
  10843. };
  10844. Node.prototype.dispose = function () {
  10845. this.parent = null;
  10846. // Callback
  10847. this.onDisposeObservable.notifyObservers(this);
  10848. this.onDisposeObservable.clear();
  10849. };
  10850. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10851. if (parsedNode.ranges) {
  10852. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10853. var data = parsedNode.ranges[index];
  10854. node.createAnimationRange(data.name, data.from, data.to);
  10855. }
  10856. }
  10857. };
  10858. return Node;
  10859. }());
  10860. __decorate([
  10861. BABYLON.serialize()
  10862. ], Node.prototype, "name", void 0);
  10863. __decorate([
  10864. BABYLON.serialize()
  10865. ], Node.prototype, "id", void 0);
  10866. __decorate([
  10867. BABYLON.serialize()
  10868. ], Node.prototype, "uniqueId", void 0);
  10869. __decorate([
  10870. BABYLON.serialize()
  10871. ], Node.prototype, "state", void 0);
  10872. __decorate([
  10873. BABYLON.serialize()
  10874. ], Node.prototype, "metadata", void 0);
  10875. BABYLON.Node = Node;
  10876. })(BABYLON || (BABYLON = {}));
  10877. //# sourceMappingURL=babylon.node.js.map
  10878. var BABYLON;
  10879. (function (BABYLON) {
  10880. var BoundingSphere = (function () {
  10881. function BoundingSphere(minimum, maximum) {
  10882. this.minimum = minimum;
  10883. this.maximum = maximum;
  10884. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10885. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10886. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10887. this.radius = distance * 0.5;
  10888. this.centerWorld = BABYLON.Vector3.Zero();
  10889. this._update(BABYLON.Matrix.Identity());
  10890. }
  10891. // Methods
  10892. BoundingSphere.prototype._update = function (world) {
  10893. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10894. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10895. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10896. };
  10897. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10898. for (var i = 0; i < 6; i++) {
  10899. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10900. return false;
  10901. }
  10902. return true;
  10903. };
  10904. BoundingSphere.prototype.intersectsPoint = function (point) {
  10905. var x = this.centerWorld.x - point.x;
  10906. var y = this.centerWorld.y - point.y;
  10907. var z = this.centerWorld.z - point.z;
  10908. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10909. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10910. return false;
  10911. return true;
  10912. };
  10913. // Statics
  10914. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10915. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10916. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10917. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10918. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10919. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10920. return false;
  10921. return true;
  10922. };
  10923. return BoundingSphere;
  10924. }());
  10925. BABYLON.BoundingSphere = BoundingSphere;
  10926. })(BABYLON || (BABYLON = {}));
  10927. //# sourceMappingURL=babylon.boundingSphere.js.map
  10928. var BABYLON;
  10929. (function (BABYLON) {
  10930. var BoundingBox = (function () {
  10931. function BoundingBox(minimum, maximum) {
  10932. this.minimum = minimum;
  10933. this.maximum = maximum;
  10934. this.vectors = new Array();
  10935. this.vectorsWorld = new Array();
  10936. // Bounding vectors
  10937. this.vectors.push(this.minimum.clone());
  10938. this.vectors.push(this.maximum.clone());
  10939. this.vectors.push(this.minimum.clone());
  10940. this.vectors[2].x = this.maximum.x;
  10941. this.vectors.push(this.minimum.clone());
  10942. this.vectors[3].y = this.maximum.y;
  10943. this.vectors.push(this.minimum.clone());
  10944. this.vectors[4].z = this.maximum.z;
  10945. this.vectors.push(this.maximum.clone());
  10946. this.vectors[5].z = this.minimum.z;
  10947. this.vectors.push(this.maximum.clone());
  10948. this.vectors[6].x = this.minimum.x;
  10949. this.vectors.push(this.maximum.clone());
  10950. this.vectors[7].y = this.minimum.y;
  10951. // OBB
  10952. this.center = this.maximum.add(this.minimum).scale(0.5);
  10953. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10954. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10955. // World
  10956. for (var index = 0; index < this.vectors.length; index++) {
  10957. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10958. }
  10959. this.minimumWorld = BABYLON.Vector3.Zero();
  10960. this.maximumWorld = BABYLON.Vector3.Zero();
  10961. this.centerWorld = BABYLON.Vector3.Zero();
  10962. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10963. this._update(BABYLON.Matrix.Identity());
  10964. }
  10965. // Methods
  10966. BoundingBox.prototype.getWorldMatrix = function () {
  10967. return this._worldMatrix;
  10968. };
  10969. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10970. this._worldMatrix.copyFrom(matrix);
  10971. return this;
  10972. };
  10973. BoundingBox.prototype._update = function (world) {
  10974. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10975. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10976. for (var index = 0; index < this.vectors.length; index++) {
  10977. var v = this.vectorsWorld[index];
  10978. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10979. if (v.x < this.minimumWorld.x)
  10980. this.minimumWorld.x = v.x;
  10981. if (v.y < this.minimumWorld.y)
  10982. this.minimumWorld.y = v.y;
  10983. if (v.z < this.minimumWorld.z)
  10984. this.minimumWorld.z = v.z;
  10985. if (v.x > this.maximumWorld.x)
  10986. this.maximumWorld.x = v.x;
  10987. if (v.y > this.maximumWorld.y)
  10988. this.maximumWorld.y = v.y;
  10989. if (v.z > this.maximumWorld.z)
  10990. this.maximumWorld.z = v.z;
  10991. }
  10992. // Extend
  10993. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10994. this.extendSizeWorld.scaleInPlace(0.5);
  10995. // OBB
  10996. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10997. this.centerWorld.scaleInPlace(0.5);
  10998. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10999. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11000. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11001. this._worldMatrix = world;
  11002. };
  11003. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11004. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11005. };
  11006. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11007. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11008. };
  11009. BoundingBox.prototype.intersectsPoint = function (point) {
  11010. var delta = -BABYLON.Epsilon;
  11011. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11012. return false;
  11013. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11014. return false;
  11015. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11016. return false;
  11017. return true;
  11018. };
  11019. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11020. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11021. };
  11022. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11023. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11024. return false;
  11025. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11026. return false;
  11027. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11028. return false;
  11029. return true;
  11030. };
  11031. // Statics
  11032. BoundingBox.Intersects = function (box0, box1) {
  11033. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11034. return false;
  11035. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11036. return false;
  11037. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11038. return false;
  11039. return true;
  11040. };
  11041. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11042. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11043. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11044. return (num <= (sphereRadius * sphereRadius));
  11045. };
  11046. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11047. for (var p = 0; p < 6; p++) {
  11048. for (var i = 0; i < 8; i++) {
  11049. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11050. return false;
  11051. }
  11052. }
  11053. }
  11054. return true;
  11055. };
  11056. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11057. for (var p = 0; p < 6; p++) {
  11058. var inCount = 8;
  11059. for (var i = 0; i < 8; i++) {
  11060. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11061. --inCount;
  11062. }
  11063. else {
  11064. break;
  11065. }
  11066. }
  11067. if (inCount === 0)
  11068. return false;
  11069. }
  11070. return true;
  11071. };
  11072. return BoundingBox;
  11073. }());
  11074. BABYLON.BoundingBox = BoundingBox;
  11075. })(BABYLON || (BABYLON = {}));
  11076. //# sourceMappingURL=babylon.boundingBox.js.map
  11077. var BABYLON;
  11078. (function (BABYLON) {
  11079. var computeBoxExtents = function (axis, box) {
  11080. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11081. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11082. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11083. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11084. var r = r0 + r1 + r2;
  11085. return {
  11086. min: p - r,
  11087. max: p + r
  11088. };
  11089. };
  11090. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11091. var axisOverlap = function (axis, box0, box1) {
  11092. var result0 = computeBoxExtents(axis, box0);
  11093. var result1 = computeBoxExtents(axis, box1);
  11094. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11095. };
  11096. var BoundingInfo = (function () {
  11097. function BoundingInfo(minimum, maximum) {
  11098. this.minimum = minimum;
  11099. this.maximum = maximum;
  11100. this._isLocked = false;
  11101. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11102. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11103. }
  11104. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11105. get: function () {
  11106. return this._isLocked;
  11107. },
  11108. set: function (value) {
  11109. this._isLocked = value;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. // Methods
  11115. BoundingInfo.prototype.update = function (world) {
  11116. if (this._isLocked) {
  11117. return;
  11118. }
  11119. this.boundingBox._update(world);
  11120. this.boundingSphere._update(world);
  11121. };
  11122. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11123. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11124. return false;
  11125. return this.boundingBox.isInFrustum(frustumPlanes);
  11126. };
  11127. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11128. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11129. };
  11130. BoundingInfo.prototype._checkCollision = function (collider) {
  11131. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11132. };
  11133. BoundingInfo.prototype.intersectsPoint = function (point) {
  11134. if (!this.boundingSphere.centerWorld) {
  11135. return false;
  11136. }
  11137. if (!this.boundingSphere.intersectsPoint(point)) {
  11138. return false;
  11139. }
  11140. if (!this.boundingBox.intersectsPoint(point)) {
  11141. return false;
  11142. }
  11143. return true;
  11144. };
  11145. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11146. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11147. return false;
  11148. }
  11149. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11150. return false;
  11151. }
  11152. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11153. return false;
  11154. }
  11155. if (!precise) {
  11156. return true;
  11157. }
  11158. var box0 = this.boundingBox;
  11159. var box1 = boundingInfo.boundingBox;
  11160. if (!axisOverlap(box0.directions[0], box0, box1))
  11161. return false;
  11162. if (!axisOverlap(box0.directions[1], box0, box1))
  11163. return false;
  11164. if (!axisOverlap(box0.directions[2], box0, box1))
  11165. return false;
  11166. if (!axisOverlap(box1.directions[0], box0, box1))
  11167. return false;
  11168. if (!axisOverlap(box1.directions[1], box0, box1))
  11169. return false;
  11170. if (!axisOverlap(box1.directions[2], box0, box1))
  11171. return false;
  11172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11173. return false;
  11174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11175. return false;
  11176. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11177. return false;
  11178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11179. return false;
  11180. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11181. return false;
  11182. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11183. return false;
  11184. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11185. return false;
  11186. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11187. return false;
  11188. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11189. return false;
  11190. return true;
  11191. };
  11192. return BoundingInfo;
  11193. }());
  11194. BABYLON.BoundingInfo = BoundingInfo;
  11195. })(BABYLON || (BABYLON = {}));
  11196. //# sourceMappingURL=babylon.boundingInfo.js.map
  11197. var BABYLON;
  11198. (function (BABYLON) {
  11199. var AbstractMesh = (function (_super) {
  11200. __extends(AbstractMesh, _super);
  11201. // Constructor
  11202. function AbstractMesh(name, scene) {
  11203. var _this = _super.call(this, name, scene) || this;
  11204. _this._facetNb = 0; // facet number
  11205. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11206. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11207. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11208. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11209. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11210. _this._subDiv = {
  11211. max: 1,
  11212. X: 1,
  11213. Y: 1,
  11214. Z: 1
  11215. };
  11216. // Events
  11217. /**
  11218. * An event triggered when this mesh collides with another one
  11219. * @type {BABYLON.Observable}
  11220. */
  11221. _this.onCollideObservable = new BABYLON.Observable();
  11222. /**
  11223. * An event triggered when the collision's position changes
  11224. * @type {BABYLON.Observable}
  11225. */
  11226. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11227. /**
  11228. * An event triggered after the world matrix is updated
  11229. * @type {BABYLON.Observable}
  11230. */
  11231. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11232. // Properties
  11233. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11234. _this.position = BABYLON.Vector3.Zero();
  11235. _this._rotation = BABYLON.Vector3.Zero();
  11236. _this._scaling = BABYLON.Vector3.One();
  11237. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11238. _this.visibility = 1.0;
  11239. _this.alphaIndex = Number.MAX_VALUE;
  11240. _this.infiniteDistance = false;
  11241. _this.isVisible = true;
  11242. _this.isPickable = true;
  11243. _this.showBoundingBox = false;
  11244. _this.showSubMeshesBoundingBox = false;
  11245. _this.isBlocker = false;
  11246. _this.renderingGroupId = 0;
  11247. _this._receiveShadows = false;
  11248. _this.renderOutline = false;
  11249. _this.outlineColor = BABYLON.Color3.Red();
  11250. _this.outlineWidth = 0.02;
  11251. _this.renderOverlay = false;
  11252. _this.overlayColor = BABYLON.Color3.Red();
  11253. _this.overlayAlpha = 0.5;
  11254. _this._hasVertexAlpha = false;
  11255. _this._useVertexColors = true;
  11256. _this._computeBonesUsingShaders = true;
  11257. _this._numBoneInfluencers = 4;
  11258. _this._applyFog = true;
  11259. _this.scalingDeterminant = 1;
  11260. _this.useOctreeForRenderingSelection = true;
  11261. _this.useOctreeForPicking = true;
  11262. _this.useOctreeForCollisions = true;
  11263. _this.layerMask = 0x0FFFFFFF;
  11264. /**
  11265. * True if the mesh must be rendered in any case.
  11266. */
  11267. _this.alwaysSelectAsActiveMesh = false;
  11268. // Collisions
  11269. _this._checkCollisions = false;
  11270. _this._collisionMask = -1;
  11271. _this._collisionGroup = -1;
  11272. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11273. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11274. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11275. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11276. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11277. // Edges
  11278. _this.edgesWidth = 1;
  11279. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11280. // Cache
  11281. _this._localWorld = BABYLON.Matrix.Zero();
  11282. _this._worldMatrix = BABYLON.Matrix.Zero();
  11283. _this._absolutePosition = BABYLON.Vector3.Zero();
  11284. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11285. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11286. _this._isDirty = false;
  11287. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11288. _this._isDisposed = false;
  11289. _this._renderId = 0;
  11290. _this._intersectionsInProgress = new Array();
  11291. _this._isWorldMatrixFrozen = false;
  11292. _this._unIndexed = false;
  11293. _this._lightSources = new Array();
  11294. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11295. if (collidedMesh === void 0) { collidedMesh = null; }
  11296. //TODO move this to the collision coordinator!
  11297. if (_this.getScene().workerCollisions)
  11298. newPosition.multiplyInPlace(_this._collider.radius);
  11299. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11300. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11301. _this.position.addInPlace(_this._diffPositionForCollisions);
  11302. }
  11303. if (collidedMesh) {
  11304. _this.onCollideObservable.notifyObservers(collidedMesh);
  11305. }
  11306. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11307. };
  11308. _this.getScene().addMesh(_this);
  11309. _this._resyncLightSources();
  11310. return _this;
  11311. }
  11312. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11313. get: function () {
  11314. return AbstractMesh._BILLBOARDMODE_NONE;
  11315. },
  11316. enumerable: true,
  11317. configurable: true
  11318. });
  11319. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11320. get: function () {
  11321. return AbstractMesh._BILLBOARDMODE_X;
  11322. },
  11323. enumerable: true,
  11324. configurable: true
  11325. });
  11326. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11327. get: function () {
  11328. return AbstractMesh._BILLBOARDMODE_Y;
  11329. },
  11330. enumerable: true,
  11331. configurable: true
  11332. });
  11333. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11334. get: function () {
  11335. return AbstractMesh._BILLBOARDMODE_Z;
  11336. },
  11337. enumerable: true,
  11338. configurable: true
  11339. });
  11340. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11341. get: function () {
  11342. return AbstractMesh._BILLBOARDMODE_ALL;
  11343. },
  11344. enumerable: true,
  11345. configurable: true
  11346. });
  11347. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11348. /**
  11349. * Read-only : the number of facets in the mesh
  11350. */
  11351. get: function () {
  11352. return this._facetNb;
  11353. },
  11354. enumerable: true,
  11355. configurable: true
  11356. });
  11357. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11358. /**
  11359. * The number (integer) of subdivisions per axis in the partioning space
  11360. */
  11361. get: function () {
  11362. return this._partitioningSubdivisions;
  11363. },
  11364. set: function (nb) {
  11365. this._partitioningSubdivisions = nb;
  11366. },
  11367. enumerable: true,
  11368. configurable: true
  11369. });
  11370. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11371. /**
  11372. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11373. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11374. */
  11375. get: function () {
  11376. return this._partitioningBBoxRatio;
  11377. },
  11378. set: function (ratio) {
  11379. this._partitioningBBoxRatio = ratio;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11385. /**
  11386. * Read-only boolean : is the feature facetData enabled ?
  11387. */
  11388. get: function () {
  11389. return this._facetDataEnabled;
  11390. },
  11391. enumerable: true,
  11392. configurable: true
  11393. });
  11394. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11395. set: function (callback) {
  11396. if (this._onCollideObserver) {
  11397. this.onCollideObservable.remove(this._onCollideObserver);
  11398. }
  11399. this._onCollideObserver = this.onCollideObservable.add(callback);
  11400. },
  11401. enumerable: true,
  11402. configurable: true
  11403. });
  11404. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11405. set: function (callback) {
  11406. if (this._onCollisionPositionChangeObserver) {
  11407. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11408. }
  11409. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11410. },
  11411. enumerable: true,
  11412. configurable: true
  11413. });
  11414. Object.defineProperty(AbstractMesh.prototype, "material", {
  11415. get: function () {
  11416. return this._material;
  11417. },
  11418. set: function (value) {
  11419. if (this._material === value) {
  11420. return;
  11421. }
  11422. this._material = value;
  11423. if (!this.subMeshes) {
  11424. return;
  11425. }
  11426. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11427. var subMesh = _a[_i];
  11428. subMesh.setEffect(null);
  11429. }
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11435. get: function () {
  11436. return this._receiveShadows;
  11437. },
  11438. set: function (value) {
  11439. if (this._receiveShadows === value) {
  11440. return;
  11441. }
  11442. this._receiveShadows = value;
  11443. this._markSubMeshesAsLightDirty();
  11444. },
  11445. enumerable: true,
  11446. configurable: true
  11447. });
  11448. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11449. get: function () {
  11450. return this._hasVertexAlpha;
  11451. },
  11452. set: function (value) {
  11453. if (this._hasVertexAlpha === value) {
  11454. return;
  11455. }
  11456. this._hasVertexAlpha = value;
  11457. this._markSubMeshesAsAttributesDirty();
  11458. },
  11459. enumerable: true,
  11460. configurable: true
  11461. });
  11462. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11463. get: function () {
  11464. return this._useVertexColors;
  11465. },
  11466. set: function (value) {
  11467. if (this._useVertexColors === value) {
  11468. return;
  11469. }
  11470. this._useVertexColors = value;
  11471. this._markSubMeshesAsAttributesDirty();
  11472. },
  11473. enumerable: true,
  11474. configurable: true
  11475. });
  11476. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11477. get: function () {
  11478. return this._computeBonesUsingShaders;
  11479. },
  11480. set: function (value) {
  11481. if (this._computeBonesUsingShaders === value) {
  11482. return;
  11483. }
  11484. this._computeBonesUsingShaders = value;
  11485. this._markSubMeshesAsAttributesDirty();
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11491. get: function () {
  11492. return this._numBoneInfluencers;
  11493. },
  11494. set: function (value) {
  11495. if (this._numBoneInfluencers === value) {
  11496. return;
  11497. }
  11498. this._numBoneInfluencers = value;
  11499. this._markSubMeshesAsAttributesDirty();
  11500. },
  11501. enumerable: true,
  11502. configurable: true
  11503. });
  11504. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11505. get: function () {
  11506. return this._applyFog;
  11507. },
  11508. set: function (value) {
  11509. if (this._applyFog === value) {
  11510. return;
  11511. }
  11512. this._applyFog = value;
  11513. this._markSubMeshesAsMiscDirty();
  11514. },
  11515. enumerable: true,
  11516. configurable: true
  11517. });
  11518. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11519. get: function () {
  11520. return this._collisionMask;
  11521. },
  11522. set: function (mask) {
  11523. this._collisionMask = !isNaN(mask) ? mask : -1;
  11524. },
  11525. enumerable: true,
  11526. configurable: true
  11527. });
  11528. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11529. get: function () {
  11530. return this._collisionGroup;
  11531. },
  11532. set: function (mask) {
  11533. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11534. },
  11535. enumerable: true,
  11536. configurable: true
  11537. });
  11538. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11539. get: function () {
  11540. return null;
  11541. },
  11542. enumerable: true,
  11543. configurable: true
  11544. });
  11545. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11546. get: function () {
  11547. return this._skeleton;
  11548. },
  11549. set: function (value) {
  11550. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11551. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11552. }
  11553. if (value && value.needInitialSkinMatrix) {
  11554. value._registerMeshWithPoseMatrix(this);
  11555. }
  11556. this._skeleton = value;
  11557. if (!this._skeleton) {
  11558. this._bonesTransformMatrices = null;
  11559. }
  11560. this._markSubMeshesAsAttributesDirty();
  11561. },
  11562. enumerable: true,
  11563. configurable: true
  11564. });
  11565. /**
  11566. * Returns the string "AbstractMesh"
  11567. */
  11568. AbstractMesh.prototype.getClassName = function () {
  11569. return "AbstractMesh";
  11570. };
  11571. /**
  11572. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11573. */
  11574. AbstractMesh.prototype.toString = function (fullDetails) {
  11575. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11576. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11577. if (this._skeleton) {
  11578. ret += ", skeleton: " + this._skeleton.name;
  11579. }
  11580. if (fullDetails) {
  11581. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11582. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11583. }
  11584. return ret;
  11585. };
  11586. AbstractMesh.prototype._resyncLightSources = function () {
  11587. this._lightSources.length = 0;
  11588. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11589. var light = _a[_i];
  11590. if (!light.isEnabled()) {
  11591. continue;
  11592. }
  11593. if (light.canAffectMesh(this)) {
  11594. this._lightSources.push(light);
  11595. }
  11596. }
  11597. this._markSubMeshesAsLightDirty();
  11598. };
  11599. AbstractMesh.prototype._resyncLighSource = function (light) {
  11600. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11601. var index = this._lightSources.indexOf(light);
  11602. if (index === -1) {
  11603. if (!isIn) {
  11604. return;
  11605. }
  11606. this._lightSources.push(light);
  11607. }
  11608. else {
  11609. if (isIn) {
  11610. return;
  11611. }
  11612. this._lightSources.splice(index, 1);
  11613. }
  11614. this._markSubMeshesAsLightDirty();
  11615. };
  11616. AbstractMesh.prototype._removeLightSource = function (light) {
  11617. var index = this._lightSources.indexOf(light);
  11618. if (index === -1) {
  11619. return;
  11620. }
  11621. this._lightSources.splice(index, 1);
  11622. };
  11623. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11624. if (!this.subMeshes) {
  11625. return;
  11626. }
  11627. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11628. var subMesh = _a[_i];
  11629. if (subMesh._materialDefines) {
  11630. func(subMesh._materialDefines);
  11631. }
  11632. }
  11633. };
  11634. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11635. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11636. };
  11637. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11638. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11639. };
  11640. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11641. if (!this.subMeshes) {
  11642. return;
  11643. }
  11644. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11645. var subMesh = _a[_i];
  11646. var material = subMesh.getMaterial();
  11647. if (material) {
  11648. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11649. }
  11650. }
  11651. };
  11652. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11653. /**
  11654. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11655. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11656. * Default : (0.0, 0.0, 0.0)
  11657. */
  11658. get: function () {
  11659. return this._rotation;
  11660. },
  11661. set: function (newRotation) {
  11662. this._rotation = newRotation;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11668. /**
  11669. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11670. * Default : (1.0, 1.0, 1.0)
  11671. */
  11672. get: function () {
  11673. return this._scaling;
  11674. },
  11675. set: function (newScaling) {
  11676. this._scaling = newScaling;
  11677. if (this.physicsImpostor) {
  11678. this.physicsImpostor.forceUpdate();
  11679. }
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11685. /**
  11686. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11687. * It's null by default.
  11688. * 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)
  11689. */
  11690. get: function () {
  11691. return this._rotationQuaternion;
  11692. },
  11693. set: function (quaternion) {
  11694. this._rotationQuaternion = quaternion;
  11695. //reset the rotation vector.
  11696. if (quaternion && this.rotation.length()) {
  11697. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11698. }
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. // Methods
  11704. /**
  11705. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11706. * Returns the AbstractMesh.
  11707. */
  11708. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11709. this._poseMatrix.copyFrom(matrix);
  11710. return this;
  11711. };
  11712. /**
  11713. * Returns the mesh Pose matrix.
  11714. * Returned object : Matrix
  11715. */
  11716. AbstractMesh.prototype.getPoseMatrix = function () {
  11717. return this._poseMatrix;
  11718. };
  11719. /**
  11720. * Disables the mesh edger rendering mode.
  11721. * Returns the AbstractMesh.
  11722. */
  11723. AbstractMesh.prototype.disableEdgesRendering = function () {
  11724. if (this._edgesRenderer !== undefined) {
  11725. this._edgesRenderer.dispose();
  11726. this._edgesRenderer = undefined;
  11727. }
  11728. return this;
  11729. };
  11730. /**
  11731. * Enables the edge rendering mode on the mesh.
  11732. * This mode makes the mesh edges visible.
  11733. * Returns the AbstractMesh.
  11734. */
  11735. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11736. if (epsilon === void 0) { epsilon = 0.95; }
  11737. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11738. this.disableEdgesRendering();
  11739. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11740. return this;
  11741. };
  11742. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11743. /**
  11744. * Returns true if the mesh is blocked. Used by the class Mesh.
  11745. * Returns the boolean `false` by default.
  11746. */
  11747. get: function () {
  11748. return false;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. /**
  11754. * Returns the mesh itself by default, used by the class Mesh.
  11755. * Returned type : AbstractMesh
  11756. */
  11757. AbstractMesh.prototype.getLOD = function (camera) {
  11758. return this;
  11759. };
  11760. /**
  11761. * Returns 0 by default, used by the class Mesh.
  11762. * Returns an integer.
  11763. */
  11764. AbstractMesh.prototype.getTotalVertices = function () {
  11765. return 0;
  11766. };
  11767. /**
  11768. * Returns null by default, used by the class Mesh.
  11769. * Returned type : integer array
  11770. */
  11771. AbstractMesh.prototype.getIndices = function () {
  11772. return null;
  11773. };
  11774. /**
  11775. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11776. * Returned type : float array or Float32Array
  11777. */
  11778. AbstractMesh.prototype.getVerticesData = function (kind) {
  11779. return null;
  11780. };
  11781. /**
  11782. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11783. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11784. * The `data` are either a numeric array either a Float32Array.
  11785. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11786. * 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).
  11787. * Note that a new underlying VertexBuffer object is created each call.
  11788. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11789. *
  11790. * Possible `kind` values :
  11791. * - BABYLON.VertexBuffer.PositionKind
  11792. * - BABYLON.VertexBuffer.UVKind
  11793. * - BABYLON.VertexBuffer.UV2Kind
  11794. * - BABYLON.VertexBuffer.UV3Kind
  11795. * - BABYLON.VertexBuffer.UV4Kind
  11796. * - BABYLON.VertexBuffer.UV5Kind
  11797. * - BABYLON.VertexBuffer.UV6Kind
  11798. * - BABYLON.VertexBuffer.ColorKind
  11799. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11800. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11801. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11802. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11803. *
  11804. * Returns the Mesh.
  11805. */
  11806. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11807. return null;
  11808. };
  11809. /**
  11810. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11811. * If the mesh has no geometry, it is simply returned as it is.
  11812. * The `data` are either a numeric array either a Float32Array.
  11813. * No new underlying VertexBuffer object is created.
  11814. * 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.
  11815. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11816. *
  11817. * Possible `kind` values :
  11818. * - BABYLON.VertexBuffer.PositionKind
  11819. * - BABYLON.VertexBuffer.UVKind
  11820. * - BABYLON.VertexBuffer.UV2Kind
  11821. * - BABYLON.VertexBuffer.UV3Kind
  11822. * - BABYLON.VertexBuffer.UV4Kind
  11823. * - BABYLON.VertexBuffer.UV5Kind
  11824. * - BABYLON.VertexBuffer.UV6Kind
  11825. * - BABYLON.VertexBuffer.ColorKind
  11826. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11827. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11828. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11829. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11830. *
  11831. * Returns the Mesh.
  11832. */
  11833. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11834. return null;
  11835. };
  11836. /**
  11837. * Sets the mesh indices.
  11838. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11839. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11840. * This method creates a new index buffer each call.
  11841. * Returns the Mesh.
  11842. */
  11843. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11844. return null;
  11845. };
  11846. /** Returns false by default, used by the class Mesh.
  11847. * Returns a boolean
  11848. */
  11849. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11850. return false;
  11851. };
  11852. /**
  11853. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11854. * Returns a BoundingInfo
  11855. */
  11856. AbstractMesh.prototype.getBoundingInfo = function () {
  11857. if (this._masterMesh) {
  11858. return this._masterMesh.getBoundingInfo();
  11859. }
  11860. if (!this._boundingInfo) {
  11861. this._updateBoundingInfo();
  11862. }
  11863. return this._boundingInfo;
  11864. };
  11865. /**
  11866. * Sets a mesh new object BoundingInfo.
  11867. * Returns the AbstractMesh.
  11868. */
  11869. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11870. this._boundingInfo = boundingInfo;
  11871. return this;
  11872. };
  11873. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11874. get: function () {
  11875. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. AbstractMesh.prototype._preActivate = function () {
  11881. };
  11882. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11883. };
  11884. AbstractMesh.prototype._activate = function (renderId) {
  11885. this._renderId = renderId;
  11886. };
  11887. /**
  11888. * Returns the last update of the World matrix
  11889. * Returns a Matrix.
  11890. */
  11891. AbstractMesh.prototype.getWorldMatrix = function () {
  11892. if (this._masterMesh) {
  11893. return this._masterMesh.getWorldMatrix();
  11894. }
  11895. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11896. this.computeWorldMatrix();
  11897. }
  11898. return this._worldMatrix;
  11899. };
  11900. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11901. /**
  11902. * Returns directly the last state of the mesh World matrix.
  11903. * A Matrix is returned.
  11904. */
  11905. get: function () {
  11906. return this._worldMatrix;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11912. /**
  11913. * Returns the current mesh absolute position.
  11914. * Retuns a Vector3.
  11915. */
  11916. get: function () {
  11917. return this._absolutePosition;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. /**
  11923. * Prevents the World matrix to be computed any longer.
  11924. * Returns the AbstractMesh.
  11925. */
  11926. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11927. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11928. this.computeWorldMatrix(true);
  11929. this._isWorldMatrixFrozen = true;
  11930. return this;
  11931. };
  11932. /**
  11933. * Allows back the World matrix computation.
  11934. * Returns the AbstractMesh.
  11935. */
  11936. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11937. this._isWorldMatrixFrozen = false;
  11938. this.computeWorldMatrix(true);
  11939. return this;
  11940. };
  11941. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11942. /**
  11943. * True if the World matrix has been frozen.
  11944. * Returns a boolean.
  11945. */
  11946. get: function () {
  11947. return this._isWorldMatrixFrozen;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. /**
  11953. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11954. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11955. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11956. * The passed axis is also normalized.
  11957. * Returns the AbstractMesh.
  11958. */
  11959. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11960. axis.normalize();
  11961. if (!this.rotationQuaternion) {
  11962. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11963. this.rotation = BABYLON.Vector3.Zero();
  11964. }
  11965. var rotationQuaternion;
  11966. if (!space || space === BABYLON.Space.LOCAL) {
  11967. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11968. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11969. }
  11970. else {
  11971. if (this.parent) {
  11972. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11973. invertParentWorldMatrix.invert();
  11974. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11975. }
  11976. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11977. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11978. }
  11979. return this;
  11980. };
  11981. /**
  11982. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  11983. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11984. * The passed axis is also normalized.
  11985. * Returns the AbstractMesh.
  11986. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  11987. */
  11988. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  11989. axis.normalize();
  11990. if (!this.rotationQuaternion) {
  11991. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11992. this.rotation.copyFromFloats(0, 0, 0);
  11993. }
  11994. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  11995. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  11996. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  11997. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  11998. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  11999. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12000. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12001. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12002. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12003. return this;
  12004. };
  12005. /**
  12006. * Translates the mesh along the axis vector for the passed distance in the given space.
  12007. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12008. * Returns the AbstractMesh.
  12009. */
  12010. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12011. var displacementVector = axis.scale(distance);
  12012. if (!space || space === BABYLON.Space.LOCAL) {
  12013. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12014. this.setPositionWithLocalVector(tempV3);
  12015. }
  12016. else {
  12017. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12018. }
  12019. return this;
  12020. };
  12021. /**
  12022. * Adds a rotation step to the mesh current rotation.
  12023. * x, y, z are Euler angles expressed in radians.
  12024. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12025. * This means this rotation is made in the mesh local space only.
  12026. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12027. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12028. * ```javascript
  12029. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12030. * ```
  12031. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12032. * 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.
  12033. * Returns the AbstractMesh.
  12034. */
  12035. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12036. var rotationQuaternion;
  12037. if (this.rotationQuaternion) {
  12038. rotationQuaternion = this.rotationQuaternion;
  12039. }
  12040. else {
  12041. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12042. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12043. }
  12044. var accumulation = BABYLON.Tmp.Quaternion[0];
  12045. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12046. rotationQuaternion.multiplyInPlace(accumulation);
  12047. if (!this.rotationQuaternion) {
  12048. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12049. }
  12050. return this;
  12051. };
  12052. /**
  12053. * Retuns the mesh absolute position in the World.
  12054. * Returns a Vector3.
  12055. */
  12056. AbstractMesh.prototype.getAbsolutePosition = function () {
  12057. this.computeWorldMatrix();
  12058. return this._absolutePosition;
  12059. };
  12060. /**
  12061. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12062. * Returns the AbstractMesh.
  12063. */
  12064. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12065. if (!absolutePosition) {
  12066. return;
  12067. }
  12068. var absolutePositionX;
  12069. var absolutePositionY;
  12070. var absolutePositionZ;
  12071. if (absolutePosition.x === undefined) {
  12072. if (arguments.length < 3) {
  12073. return;
  12074. }
  12075. absolutePositionX = arguments[0];
  12076. absolutePositionY = arguments[1];
  12077. absolutePositionZ = arguments[2];
  12078. }
  12079. else {
  12080. absolutePositionX = absolutePosition.x;
  12081. absolutePositionY = absolutePosition.y;
  12082. absolutePositionZ = absolutePosition.z;
  12083. }
  12084. if (this.parent) {
  12085. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12086. invertParentWorldMatrix.invert();
  12087. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12088. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12089. }
  12090. else {
  12091. this.position.x = absolutePositionX;
  12092. this.position.y = absolutePositionY;
  12093. this.position.z = absolutePositionZ;
  12094. }
  12095. return this;
  12096. };
  12097. // ================================== Point of View Movement =================================
  12098. /**
  12099. * Perform relative position change from the point of view of behind the front of the mesh.
  12100. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12101. * Supports definition of mesh facing forward or backward.
  12102. * @param {number} amountRight
  12103. * @param {number} amountUp
  12104. * @param {number} amountForward
  12105. *
  12106. * Returns the AbstractMesh.
  12107. */
  12108. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12109. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12110. return this;
  12111. };
  12112. /**
  12113. * Calculate relative position change from the point of view of behind the front of the mesh.
  12114. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12115. * Supports definition of mesh facing forward or backward.
  12116. * @param {number} amountRight
  12117. * @param {number} amountUp
  12118. * @param {number} amountForward
  12119. *
  12120. * Returns a new Vector3.
  12121. */
  12122. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12123. var rotMatrix = new BABYLON.Matrix();
  12124. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12125. rotQuaternion.toRotationMatrix(rotMatrix);
  12126. var translationDelta = BABYLON.Vector3.Zero();
  12127. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12128. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12129. return translationDelta;
  12130. };
  12131. // ================================== Point of View Rotation =================================
  12132. /**
  12133. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12134. * Supports definition of mesh facing forward or backward.
  12135. * @param {number} flipBack
  12136. * @param {number} twirlClockwise
  12137. * @param {number} tiltRight
  12138. *
  12139. * Returns the AbstractMesh.
  12140. */
  12141. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12142. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12143. return this;
  12144. };
  12145. /**
  12146. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12147. * Supports definition of mesh facing forward or backward.
  12148. * @param {number} flipBack
  12149. * @param {number} twirlClockwise
  12150. * @param {number} tiltRight
  12151. *
  12152. * Returns a new Vector3.
  12153. */
  12154. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12155. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12156. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12157. };
  12158. /**
  12159. * Sets a new pivot matrix to the mesh.
  12160. * Returns the AbstractMesh.
  12161. */
  12162. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12163. this._pivotMatrix = matrix;
  12164. this._cache.pivotMatrixUpdated = true;
  12165. return this;
  12166. };
  12167. /**
  12168. * Returns the mesh pivot matrix.
  12169. * Default : Identity.
  12170. * A Matrix is returned.
  12171. */
  12172. AbstractMesh.prototype.getPivotMatrix = function () {
  12173. return this._pivotMatrix;
  12174. };
  12175. AbstractMesh.prototype._isSynchronized = function () {
  12176. if (this._isDirty) {
  12177. return false;
  12178. }
  12179. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12180. return false;
  12181. if (this._cache.pivotMatrixUpdated) {
  12182. return false;
  12183. }
  12184. if (this.infiniteDistance) {
  12185. return false;
  12186. }
  12187. if (!this._cache.position.equals(this.position))
  12188. return false;
  12189. if (this.rotationQuaternion) {
  12190. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12191. return false;
  12192. }
  12193. if (!this._cache.rotation.equals(this.rotation))
  12194. return false;
  12195. if (!this._cache.scaling.equals(this.scaling))
  12196. return false;
  12197. return true;
  12198. };
  12199. AbstractMesh.prototype._initCache = function () {
  12200. _super.prototype._initCache.call(this);
  12201. this._cache.localMatrixUpdated = false;
  12202. this._cache.position = BABYLON.Vector3.Zero();
  12203. this._cache.scaling = BABYLON.Vector3.Zero();
  12204. this._cache.rotation = BABYLON.Vector3.Zero();
  12205. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12206. this._cache.billboardMode = -1;
  12207. };
  12208. AbstractMesh.prototype.markAsDirty = function (property) {
  12209. if (property === "rotation") {
  12210. this.rotationQuaternion = null;
  12211. }
  12212. this._currentRenderId = Number.MAX_VALUE;
  12213. this._isDirty = true;
  12214. return this;
  12215. };
  12216. /**
  12217. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12218. * Returns the AbstractMesh.
  12219. */
  12220. AbstractMesh.prototype._updateBoundingInfo = function () {
  12221. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12222. this._boundingInfo.update(this.worldMatrixFromCache);
  12223. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12224. return this;
  12225. };
  12226. /**
  12227. * Update a mesh's children BoundingInfo objects only.
  12228. * Returns the AbstractMesh.
  12229. */
  12230. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12231. if (!this.subMeshes) {
  12232. return;
  12233. }
  12234. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12235. var subMesh = this.subMeshes[subIndex];
  12236. if (!subMesh.IsGlobal) {
  12237. subMesh.updateBoundingInfo(matrix);
  12238. }
  12239. }
  12240. return this;
  12241. };
  12242. /**
  12243. * Computes the mesh World matrix and returns it.
  12244. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12245. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12246. * If the parameter `force`is set to `true`, the actual computation is done.
  12247. * Returns the mesh World Matrix.
  12248. */
  12249. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12250. if (this._isWorldMatrixFrozen) {
  12251. return this._worldMatrix;
  12252. }
  12253. if (!force && this.isSynchronized(true)) {
  12254. this._currentRenderId = this.getScene().getRenderId();
  12255. return this._worldMatrix;
  12256. }
  12257. this._cache.position.copyFrom(this.position);
  12258. this._cache.scaling.copyFrom(this.scaling);
  12259. this._cache.pivotMatrixUpdated = false;
  12260. this._cache.billboardMode = this.billboardMode;
  12261. this._currentRenderId = this.getScene().getRenderId();
  12262. this._isDirty = false;
  12263. // Scaling
  12264. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12265. // Rotation
  12266. //rotate, if quaternion is set and rotation was used
  12267. if (this.rotationQuaternion) {
  12268. var len = this.rotation.length();
  12269. if (len) {
  12270. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12271. this.rotation.copyFromFloats(0, 0, 0);
  12272. }
  12273. }
  12274. if (this.rotationQuaternion) {
  12275. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12276. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12277. }
  12278. else {
  12279. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12280. this._cache.rotation.copyFrom(this.rotation);
  12281. }
  12282. // Translation
  12283. if (this.infiniteDistance && !this.parent) {
  12284. var camera = this.getScene().activeCamera;
  12285. if (camera) {
  12286. var cameraWorldMatrix = camera.getWorldMatrix();
  12287. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12288. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12289. }
  12290. }
  12291. else {
  12292. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12293. }
  12294. // Composing transformations
  12295. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12296. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12297. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12298. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12299. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12300. // Need to decompose each rotation here
  12301. var currentPosition = BABYLON.Tmp.Vector3[3];
  12302. if (this.parent && this.parent.getWorldMatrix) {
  12303. if (this._meshToBoneReferal) {
  12304. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12305. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12306. }
  12307. else {
  12308. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12309. }
  12310. }
  12311. else {
  12312. currentPosition.copyFrom(this.position);
  12313. }
  12314. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12315. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12316. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12317. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12318. }
  12319. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12320. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12321. }
  12322. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12323. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12324. }
  12325. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12326. }
  12327. else {
  12328. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12329. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12330. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12331. }
  12332. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12333. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12334. }
  12335. // Local world
  12336. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12337. // Parent
  12338. if (this.parent && this.parent.getWorldMatrix) {
  12339. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12340. if (this._meshToBoneReferal) {
  12341. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12342. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12343. }
  12344. else {
  12345. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12346. }
  12347. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12348. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12349. this._worldMatrix.copyFrom(this._localWorld);
  12350. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12351. }
  12352. else {
  12353. if (this._meshToBoneReferal) {
  12354. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12355. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12356. }
  12357. else {
  12358. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12359. }
  12360. }
  12361. this._markSyncedWithParent();
  12362. }
  12363. else {
  12364. this._worldMatrix.copyFrom(this._localWorld);
  12365. }
  12366. // Bounding info
  12367. this._updateBoundingInfo();
  12368. // Absolute position
  12369. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12370. // Callbacks
  12371. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12372. if (!this._poseMatrix) {
  12373. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12374. }
  12375. return this._worldMatrix;
  12376. };
  12377. /**
  12378. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12379. * @param func: callback function to add
  12380. *
  12381. * Returns the AbstractMesh.
  12382. */
  12383. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12384. this.onAfterWorldMatrixUpdateObservable.add(func);
  12385. return this;
  12386. };
  12387. /**
  12388. * Removes a registered callback function.
  12389. * Returns the AbstractMesh.
  12390. */
  12391. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12392. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12393. return this;
  12394. };
  12395. /**
  12396. * Sets the mesh position in its local space.
  12397. * Returns the AbstractMesh.
  12398. */
  12399. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12400. this.computeWorldMatrix();
  12401. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12402. return this;
  12403. };
  12404. /**
  12405. * Returns the mesh position in the local space from the current World matrix values.
  12406. * Returns a new Vector3.
  12407. */
  12408. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12409. this.computeWorldMatrix();
  12410. var invLocalWorldMatrix = this._localWorld.clone();
  12411. invLocalWorldMatrix.invert();
  12412. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12413. };
  12414. /**
  12415. * Translates the mesh along the passed Vector3 in its local space.
  12416. * Returns the AbstractMesh.
  12417. */
  12418. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12419. this.computeWorldMatrix(true);
  12420. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12421. return this;
  12422. };
  12423. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12424. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12425. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12426. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12427. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12428. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12429. /// <returns>Mesh oriented towards targetMesh</returns>
  12430. if (yawCor === void 0) { yawCor = 0; }
  12431. if (pitchCor === void 0) { pitchCor = 0; }
  12432. if (rollCor === void 0) { rollCor = 0; }
  12433. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12434. var dv = AbstractMesh._lookAtVectorCache;
  12435. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12436. targetPoint.subtractToRef(pos, dv);
  12437. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12438. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12439. var pitch = Math.atan2(dv.y, len);
  12440. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12441. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12442. return this;
  12443. };
  12444. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12445. this._meshToBoneReferal = affectedMesh;
  12446. this.parent = bone;
  12447. if (bone.getWorldMatrix().determinant() < 0) {
  12448. this.scalingDeterminant *= -1;
  12449. }
  12450. return this;
  12451. };
  12452. AbstractMesh.prototype.detachFromBone = function () {
  12453. if (this.parent.getWorldMatrix().determinant() < 0) {
  12454. this.scalingDeterminant *= -1;
  12455. }
  12456. this._meshToBoneReferal = null;
  12457. this.parent = null;
  12458. return this;
  12459. };
  12460. /**
  12461. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12462. * A mesh is in the frustum if its bounding box intersects the frustum.
  12463. * Boolean returned.
  12464. */
  12465. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12466. return this._boundingInfo.isInFrustum(frustumPlanes);
  12467. };
  12468. /**
  12469. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12470. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12471. * Boolean returned.
  12472. */
  12473. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12474. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12475. ;
  12476. };
  12477. /**
  12478. * True if the mesh intersects another mesh or a SolidParticle object.
  12479. * 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)
  12480. * Returns a boolean.
  12481. */
  12482. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12483. if (!this._boundingInfo || !mesh._boundingInfo) {
  12484. return false;
  12485. }
  12486. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12487. };
  12488. /**
  12489. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12490. * Returns a boolean.
  12491. */
  12492. AbstractMesh.prototype.intersectsPoint = function (point) {
  12493. if (!this._boundingInfo) {
  12494. return false;
  12495. }
  12496. return this._boundingInfo.intersectsPoint(point);
  12497. };
  12498. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12499. return this.physicsImpostor;
  12500. };
  12501. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12502. if (!camera) {
  12503. camera = this.getScene().activeCamera;
  12504. }
  12505. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12506. };
  12507. /**
  12508. * Returns the distance from the mesh to the active camera.
  12509. * Returns a float.
  12510. */
  12511. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12512. if (!camera) {
  12513. camera = this.getScene().activeCamera;
  12514. }
  12515. return this.absolutePosition.subtract(camera.position).length();
  12516. };
  12517. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12518. if (!this.physicsImpostor) {
  12519. return;
  12520. }
  12521. this.physicsImpostor.applyImpulse(force, contactPoint);
  12522. return this;
  12523. };
  12524. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12525. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12526. return;
  12527. }
  12528. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12529. mainPivot: pivot1,
  12530. connectedPivot: pivot2,
  12531. nativeParams: options
  12532. });
  12533. return this;
  12534. };
  12535. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12536. // Collisions
  12537. /**
  12538. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12539. * Default `false`.
  12540. */
  12541. get: function () {
  12542. return this._checkCollisions;
  12543. },
  12544. set: function (collisionEnabled) {
  12545. this._checkCollisions = collisionEnabled;
  12546. if (this.getScene().workerCollisions) {
  12547. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12548. }
  12549. },
  12550. enumerable: true,
  12551. configurable: true
  12552. });
  12553. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12554. var globalPosition = this.getAbsolutePosition();
  12555. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12556. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12557. if (!this._collider) {
  12558. this._collider = new BABYLON.Collider();
  12559. }
  12560. this._collider.radius = this.ellipsoid;
  12561. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12562. return this;
  12563. };
  12564. // Submeshes octree
  12565. /**
  12566. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12567. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12568. * Returns an Octree of submeshes.
  12569. */
  12570. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12571. if (maxCapacity === void 0) { maxCapacity = 64; }
  12572. if (maxDepth === void 0) { maxDepth = 2; }
  12573. if (!this._submeshesOctree) {
  12574. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12575. }
  12576. this.computeWorldMatrix(true);
  12577. // Update octree
  12578. var bbox = this.getBoundingInfo().boundingBox;
  12579. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12580. return this._submeshesOctree;
  12581. };
  12582. // Collisions
  12583. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12584. this._generatePointsArray();
  12585. // Transformation
  12586. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12587. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12588. subMesh._lastColliderWorldVertices = [];
  12589. subMesh._trianglePlanes = [];
  12590. var start = subMesh.verticesStart;
  12591. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12592. for (var i = start; i < end; i++) {
  12593. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12594. }
  12595. }
  12596. // Collide
  12597. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12598. if (collider.collisionFound) {
  12599. collider.collidedMesh = this;
  12600. }
  12601. return this;
  12602. };
  12603. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12604. var subMeshes;
  12605. var len;
  12606. // Octrees
  12607. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12608. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12609. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12610. len = intersections.length;
  12611. subMeshes = intersections.data;
  12612. }
  12613. else {
  12614. subMeshes = this.subMeshes;
  12615. len = subMeshes.length;
  12616. }
  12617. for (var index = 0; index < len; index++) {
  12618. var subMesh = subMeshes[index];
  12619. // Bounding test
  12620. if (len > 1 && !subMesh._checkCollision(collider))
  12621. continue;
  12622. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12623. }
  12624. return this;
  12625. };
  12626. AbstractMesh.prototype._checkCollision = function (collider) {
  12627. // Bounding box test
  12628. if (!this._boundingInfo._checkCollision(collider))
  12629. return this;
  12630. // Transformation matrix
  12631. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12632. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12633. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12634. return this;
  12635. };
  12636. // Picking
  12637. AbstractMesh.prototype._generatePointsArray = function () {
  12638. return false;
  12639. };
  12640. /**
  12641. * Checks if the passed Ray intersects with the mesh.
  12642. * Returns an object PickingInfo.
  12643. */
  12644. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12645. var pickingInfo = new BABYLON.PickingInfo();
  12646. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12647. return pickingInfo;
  12648. }
  12649. if (!this._generatePointsArray()) {
  12650. return pickingInfo;
  12651. }
  12652. var intersectInfo = null;
  12653. // Octrees
  12654. var subMeshes;
  12655. var len;
  12656. if (this._submeshesOctree && this.useOctreeForPicking) {
  12657. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12658. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12659. len = intersections.length;
  12660. subMeshes = intersections.data;
  12661. }
  12662. else {
  12663. subMeshes = this.subMeshes;
  12664. len = subMeshes.length;
  12665. }
  12666. for (var index = 0; index < len; index++) {
  12667. var subMesh = subMeshes[index];
  12668. // Bounding test
  12669. if (len > 1 && !subMesh.canIntersects(ray))
  12670. continue;
  12671. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12672. if (currentIntersectInfo) {
  12673. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12674. intersectInfo = currentIntersectInfo;
  12675. intersectInfo.subMeshId = index;
  12676. if (fastCheck) {
  12677. break;
  12678. }
  12679. }
  12680. }
  12681. }
  12682. if (intersectInfo) {
  12683. // Get picked point
  12684. var world = this.getWorldMatrix();
  12685. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12686. var direction = ray.direction.clone();
  12687. direction = direction.scale(intersectInfo.distance);
  12688. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12689. var pickedPoint = worldOrigin.add(worldDirection);
  12690. // Return result
  12691. pickingInfo.hit = true;
  12692. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12693. pickingInfo.pickedPoint = pickedPoint;
  12694. pickingInfo.pickedMesh = this;
  12695. pickingInfo.bu = intersectInfo.bu;
  12696. pickingInfo.bv = intersectInfo.bv;
  12697. pickingInfo.faceId = intersectInfo.faceId;
  12698. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12699. return pickingInfo;
  12700. }
  12701. return pickingInfo;
  12702. };
  12703. /**
  12704. * Clones the mesh, used by the class Mesh.
  12705. * Just returns `null` for an AbstractMesh.
  12706. */
  12707. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12708. return null;
  12709. };
  12710. /**
  12711. * Disposes all the mesh submeshes.
  12712. * Returns the AbstractMesh.
  12713. */
  12714. AbstractMesh.prototype.releaseSubMeshes = function () {
  12715. if (this.subMeshes) {
  12716. while (this.subMeshes.length) {
  12717. this.subMeshes[0].dispose();
  12718. }
  12719. }
  12720. else {
  12721. this.subMeshes = new Array();
  12722. }
  12723. return this;
  12724. };
  12725. /**
  12726. * Disposes the AbstractMesh.
  12727. * Some internal references are kept for further use.
  12728. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12729. * Returns nothing.
  12730. */
  12731. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12732. var _this = this;
  12733. var index;
  12734. // Action manager
  12735. if (this.actionManager) {
  12736. this.actionManager.dispose();
  12737. this.actionManager = null;
  12738. }
  12739. // Skeleton
  12740. this.skeleton = null;
  12741. // Animations
  12742. this.getScene().stopAnimation(this);
  12743. // Physics
  12744. if (this.physicsImpostor) {
  12745. this.physicsImpostor.dispose();
  12746. }
  12747. // Intersections in progress
  12748. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12749. var other = this._intersectionsInProgress[index];
  12750. var pos = other._intersectionsInProgress.indexOf(this);
  12751. other._intersectionsInProgress.splice(pos, 1);
  12752. }
  12753. this._intersectionsInProgress = [];
  12754. // Lights
  12755. var lights = this.getScene().lights;
  12756. lights.forEach(function (light) {
  12757. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12758. if (meshIndex !== -1) {
  12759. light.includedOnlyMeshes.splice(meshIndex, 1);
  12760. }
  12761. meshIndex = light.excludedMeshes.indexOf(_this);
  12762. if (meshIndex !== -1) {
  12763. light.excludedMeshes.splice(meshIndex, 1);
  12764. }
  12765. // Shadow generators
  12766. var generator = light.getShadowGenerator();
  12767. if (generator) {
  12768. var shadowMap = generator.getShadowMap();
  12769. meshIndex = shadowMap.renderList.indexOf(_this);
  12770. if (meshIndex !== -1) {
  12771. shadowMap.renderList.splice(meshIndex, 1);
  12772. }
  12773. }
  12774. });
  12775. // Edges
  12776. if (this._edgesRenderer) {
  12777. this._edgesRenderer.dispose();
  12778. this._edgesRenderer = null;
  12779. }
  12780. // SubMeshes
  12781. if (this.getClassName() !== "InstancedMesh") {
  12782. this.releaseSubMeshes();
  12783. }
  12784. // Octree
  12785. var sceneOctree = this.getScene().selectionOctree;
  12786. if (sceneOctree) {
  12787. var index = sceneOctree.dynamicContent.indexOf(this);
  12788. if (index !== -1) {
  12789. sceneOctree.dynamicContent.splice(index, 1);
  12790. }
  12791. }
  12792. // Engine
  12793. this.getScene().getEngine().wipeCaches();
  12794. // Remove from scene
  12795. this.getScene().removeMesh(this);
  12796. if (!doNotRecurse) {
  12797. // Particles
  12798. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12799. if (this.getScene().particleSystems[index].emitter === this) {
  12800. this.getScene().particleSystems[index].dispose();
  12801. index--;
  12802. }
  12803. }
  12804. // Children
  12805. var objects = this.getDescendants(true);
  12806. for (index = 0; index < objects.length; index++) {
  12807. objects[index].dispose();
  12808. }
  12809. }
  12810. else {
  12811. var childMeshes = this.getChildMeshes(true);
  12812. for (index = 0; index < childMeshes.length; index++) {
  12813. var child = childMeshes[index];
  12814. child.parent = null;
  12815. child.computeWorldMatrix(true);
  12816. }
  12817. }
  12818. // facet data
  12819. if (this._facetDataEnabled) {
  12820. this.disableFacetData();
  12821. }
  12822. this.onAfterWorldMatrixUpdateObservable.clear();
  12823. this.onCollideObservable.clear();
  12824. this.onCollisionPositionChangeObservable.clear();
  12825. this._isDisposed = true;
  12826. _super.prototype.dispose.call(this);
  12827. };
  12828. /**
  12829. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12830. * This Vector3 is expressed in the World space.
  12831. */
  12832. AbstractMesh.prototype.getDirection = function (localAxis) {
  12833. var result = BABYLON.Vector3.Zero();
  12834. this.getDirectionToRef(localAxis, result);
  12835. return result;
  12836. };
  12837. /**
  12838. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12839. * localAxis is expressed in the mesh local space.
  12840. * result is computed in the Wordl space from the mesh World matrix.
  12841. * Returns the AbstractMesh.
  12842. */
  12843. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12844. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12845. return this;
  12846. };
  12847. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12848. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12849. if (this.getScene().getRenderId() == 0) {
  12850. this.computeWorldMatrix(true);
  12851. }
  12852. var wm = this.getWorldMatrix();
  12853. if (space == BABYLON.Space.WORLD) {
  12854. var tmat = BABYLON.Tmp.Matrix[0];
  12855. wm.invertToRef(tmat);
  12856. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12857. }
  12858. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12859. this._pivotMatrix.m[12] = -point.x;
  12860. this._pivotMatrix.m[13] = -point.y;
  12861. this._pivotMatrix.m[14] = -point.z;
  12862. this._cache.pivotMatrixUpdated = true;
  12863. return this;
  12864. };
  12865. /**
  12866. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12867. */
  12868. AbstractMesh.prototype.getPivotPoint = function () {
  12869. var point = BABYLON.Vector3.Zero();
  12870. this.getPivotPointToRef(point);
  12871. return point;
  12872. };
  12873. /**
  12874. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12875. * Returns the AbstractMesh.
  12876. */
  12877. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12878. result.x = -this._pivotMatrix.m[12];
  12879. result.y = -this._pivotMatrix.m[13];
  12880. result.z = -this._pivotMatrix.m[14];
  12881. return this;
  12882. };
  12883. /**
  12884. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12885. */
  12886. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12887. var point = BABYLON.Vector3.Zero();
  12888. this.getAbsolutePivotPointToRef(point);
  12889. return point;
  12890. };
  12891. /**
  12892. * Defines the passed mesh as the parent of the current mesh.
  12893. * Returns the AbstractMesh.
  12894. */
  12895. AbstractMesh.prototype.setParent = function (mesh) {
  12896. var child = this;
  12897. var parent = mesh;
  12898. if (mesh == null) {
  12899. var rotation = BABYLON.Tmp.Quaternion[0];
  12900. var position = BABYLON.Tmp.Vector3[0];
  12901. var scale = BABYLON.Tmp.Vector3[1];
  12902. child.getWorldMatrix().decompose(scale, rotation, position);
  12903. if (child.rotationQuaternion) {
  12904. child.rotationQuaternion.copyFrom(rotation);
  12905. }
  12906. else {
  12907. rotation.toEulerAnglesToRef(child.rotation);
  12908. }
  12909. child.position.x = position.x;
  12910. child.position.y = position.y;
  12911. child.position.z = position.z;
  12912. }
  12913. else {
  12914. var rotation = BABYLON.Tmp.Quaternion[0];
  12915. var position = BABYLON.Tmp.Vector3[0];
  12916. var scale = BABYLON.Tmp.Vector3[1];
  12917. var m1 = BABYLON.Tmp.Matrix[0];
  12918. var m2 = BABYLON.Tmp.Matrix[1];
  12919. parent.getWorldMatrix().decompose(scale, rotation, position);
  12920. rotation.toRotationMatrix(m1);
  12921. m2.setTranslation(position);
  12922. m2.multiplyToRef(m1, m1);
  12923. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12924. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12925. m.decompose(scale, rotation, position);
  12926. if (child.rotationQuaternion) {
  12927. child.rotationQuaternion.copyFrom(rotation);
  12928. }
  12929. else {
  12930. rotation.toEulerAnglesToRef(child.rotation);
  12931. }
  12932. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12933. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12934. m.decompose(scale, rotation, position);
  12935. child.position.x = position.x;
  12936. child.position.y = position.y;
  12937. child.position.z = position.z;
  12938. }
  12939. child.parent = parent;
  12940. return this;
  12941. };
  12942. /**
  12943. * Adds the passed mesh as a child to the current mesh.
  12944. * Returns the AbstractMesh.
  12945. */
  12946. AbstractMesh.prototype.addChild = function (mesh) {
  12947. mesh.setParent(this);
  12948. return this;
  12949. };
  12950. /**
  12951. * Removes the passed mesh from the current mesh children list.
  12952. * Returns the AbstractMesh.
  12953. */
  12954. AbstractMesh.prototype.removeChild = function (mesh) {
  12955. mesh.setParent(null);
  12956. return this;
  12957. };
  12958. /**
  12959. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12960. * Returns the AbstractMesh.
  12961. */
  12962. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12963. result.x = this._pivotMatrix.m[12];
  12964. result.y = this._pivotMatrix.m[13];
  12965. result.z = this._pivotMatrix.m[14];
  12966. this.getPivotPointToRef(result);
  12967. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12968. return this;
  12969. };
  12970. // Facet data
  12971. /**
  12972. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12973. * Returns the AbstractMesh.
  12974. */
  12975. AbstractMesh.prototype._initFacetData = function () {
  12976. if (!this._facetNormals) {
  12977. this._facetNormals = new Array();
  12978. }
  12979. if (!this._facetPositions) {
  12980. this._facetPositions = new Array();
  12981. }
  12982. if (!this._facetPartitioning) {
  12983. this._facetPartitioning = new Array();
  12984. }
  12985. this._facetNb = this.getIndices().length / 3;
  12986. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12987. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12988. for (var f = 0; f < this._facetNb; f++) {
  12989. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12990. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12991. }
  12992. this._facetDataEnabled = true;
  12993. return this;
  12994. };
  12995. /**
  12996. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12997. * This method can be called within the render loop.
  12998. * 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.
  12999. * Returns the AbstractMesh.
  13000. */
  13001. AbstractMesh.prototype.updateFacetData = function () {
  13002. if (!this._facetDataEnabled) {
  13003. this._initFacetData();
  13004. }
  13005. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13006. var indices = this.getIndices();
  13007. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13008. var bInfo = this.getBoundingInfo();
  13009. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13010. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13011. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13012. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13013. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13014. this._subDiv.max = this._partitioningSubdivisions;
  13015. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13016. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13017. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13018. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13019. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13020. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13021. // set the parameters for ComputeNormals()
  13022. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13023. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13024. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13025. this._facetParameters.bInfo = bInfo;
  13026. this._facetParameters.bbSize = this._bbSize;
  13027. this._facetParameters.subDiv = this._subDiv;
  13028. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13029. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13030. return this;
  13031. };
  13032. /**
  13033. * Returns the facetLocalNormals array.
  13034. * The normals are expressed in the mesh local space.
  13035. */
  13036. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13037. if (!this._facetNormals) {
  13038. this.updateFacetData();
  13039. }
  13040. return this._facetNormals;
  13041. };
  13042. /**
  13043. * Returns the facetLocalPositions array.
  13044. * The facet positions are expressed in the mesh local space.
  13045. */
  13046. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13047. if (!this._facetPositions) {
  13048. this.updateFacetData();
  13049. }
  13050. return this._facetPositions;
  13051. };
  13052. /**
  13053. * Returns the facetLocalPartioning array.
  13054. */
  13055. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13056. if (!this._facetPartitioning) {
  13057. this.updateFacetData();
  13058. }
  13059. return this._facetPartitioning;
  13060. };
  13061. /**
  13062. * Returns the i-th facet position in the world system.
  13063. * This method allocates a new Vector3 per call.
  13064. */
  13065. AbstractMesh.prototype.getFacetPosition = function (i) {
  13066. var pos = BABYLON.Vector3.Zero();
  13067. this.getFacetPositionToRef(i, pos);
  13068. return pos;
  13069. };
  13070. /**
  13071. * Sets the reference Vector3 with the i-th facet position in the world system.
  13072. * Returns the AbstractMesh.
  13073. */
  13074. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13075. var localPos = (this.getFacetLocalPositions())[i];
  13076. var world = this.getWorldMatrix();
  13077. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13078. return this;
  13079. };
  13080. /**
  13081. * Returns the i-th facet normal in the world system.
  13082. * This method allocates a new Vector3 per call.
  13083. */
  13084. AbstractMesh.prototype.getFacetNormal = function (i) {
  13085. var norm = BABYLON.Vector3.Zero();
  13086. this.getFacetNormalToRef(i, norm);
  13087. return norm;
  13088. };
  13089. /**
  13090. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13091. * Returns the AbstractMesh.
  13092. */
  13093. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13094. var localNorm = (this.getFacetLocalNormals())[i];
  13095. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13096. return this;
  13097. };
  13098. /**
  13099. * 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).
  13100. */
  13101. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13102. var bInfo = this.getBoundingInfo();
  13103. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13104. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13105. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13106. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13107. return null;
  13108. }
  13109. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13110. };
  13111. /**
  13112. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13113. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13114. * 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.
  13115. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13116. * 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.
  13117. */
  13118. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13119. if (checkFace === void 0) { checkFace = false; }
  13120. if (facing === void 0) { facing = true; }
  13121. var world = this.getWorldMatrix();
  13122. var invMat = BABYLON.Tmp.Matrix[5];
  13123. world.invertToRef(invMat);
  13124. var invVect = BABYLON.Tmp.Vector3[8];
  13125. var closest = null;
  13126. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13127. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13128. if (projected) {
  13129. // tranform the local computed projected vector to world coordinates
  13130. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13131. }
  13132. return closest;
  13133. };
  13134. /**
  13135. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13136. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13137. * 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.
  13138. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13139. * 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.
  13140. */
  13141. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13142. if (checkFace === void 0) { checkFace = false; }
  13143. if (facing === void 0) { facing = true; }
  13144. var closest = null;
  13145. var tmpx = 0.0;
  13146. var tmpy = 0.0;
  13147. var tmpz = 0.0;
  13148. var d = 0.0; // tmp dot facet normal * facet position
  13149. var t0 = 0.0;
  13150. var projx = 0.0;
  13151. var projy = 0.0;
  13152. var projz = 0.0;
  13153. // Get all the facets in the same partitioning block than (x, y, z)
  13154. var facetPositions = this.getFacetLocalPositions();
  13155. var facetNormals = this.getFacetLocalNormals();
  13156. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13157. if (!facetsInBlock) {
  13158. return null;
  13159. }
  13160. // Get the closest facet to (x, y, z)
  13161. var shortest = Number.MAX_VALUE; // init distance vars
  13162. var tmpDistance = shortest;
  13163. var fib; // current facet in the block
  13164. var norm; // current facet normal
  13165. var p0; // current facet barycenter position
  13166. // loop on all the facets in the current partitioning block
  13167. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13168. fib = facetsInBlock[idx];
  13169. norm = facetNormals[fib];
  13170. p0 = facetPositions[fib];
  13171. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13172. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13173. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13174. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13175. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13176. projx = x + norm.x * t0;
  13177. projy = y + norm.y * t0;
  13178. projz = z + norm.z * t0;
  13179. tmpx = projx - x;
  13180. tmpy = projy - y;
  13181. tmpz = projz - z;
  13182. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13183. if (tmpDistance < shortest) {
  13184. shortest = tmpDistance;
  13185. closest = fib;
  13186. if (projected) {
  13187. projected.x = projx;
  13188. projected.y = projy;
  13189. projected.z = projz;
  13190. }
  13191. }
  13192. }
  13193. }
  13194. return closest;
  13195. };
  13196. /**
  13197. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13198. */
  13199. AbstractMesh.prototype.getFacetDataParameters = function () {
  13200. return this._facetParameters;
  13201. };
  13202. /**
  13203. * Disables the feature FacetData and frees the related memory.
  13204. * Returns the AbstractMesh.
  13205. */
  13206. AbstractMesh.prototype.disableFacetData = function () {
  13207. if (this._facetDataEnabled) {
  13208. this._facetDataEnabled = false;
  13209. this._facetPositions = null;
  13210. this._facetNormals = null;
  13211. this._facetPartitioning = null;
  13212. this._facetParameters = null;
  13213. }
  13214. return this;
  13215. };
  13216. /**
  13217. * Creates new normals data for the mesh.
  13218. * @param updatable.
  13219. */
  13220. AbstractMesh.prototype.createNormals = function (updatable) {
  13221. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13222. var indices = this.getIndices();
  13223. var normals;
  13224. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13225. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13226. }
  13227. else {
  13228. normals = [];
  13229. }
  13230. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13231. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13232. };
  13233. return AbstractMesh;
  13234. }(BABYLON.Node));
  13235. // Statics
  13236. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13237. AbstractMesh._BILLBOARDMODE_X = 1;
  13238. AbstractMesh._BILLBOARDMODE_Y = 2;
  13239. AbstractMesh._BILLBOARDMODE_Z = 4;
  13240. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13241. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13242. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13243. BABYLON.AbstractMesh = AbstractMesh;
  13244. })(BABYLON || (BABYLON = {}));
  13245. //# sourceMappingURL=babylon.abstractMesh.js.map
  13246. var BABYLON;
  13247. (function (BABYLON) {
  13248. var Light = (function (_super) {
  13249. __extends(Light, _super);
  13250. /**
  13251. * Creates a Light object in the scene.
  13252. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13253. */
  13254. function Light(name, scene) {
  13255. var _this = _super.call(this, name, scene) || this;
  13256. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13257. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13258. _this.intensity = 1.0;
  13259. _this.range = Number.MAX_VALUE;
  13260. /**
  13261. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13262. * of light.
  13263. */
  13264. _this._photometricScale = 1.0;
  13265. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13266. _this._radius = 0.00001;
  13267. _this.renderPriority = 0;
  13268. /**
  13269. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13270. * the current shadow generator.
  13271. */
  13272. _this.shadowEnabled = true;
  13273. _this._excludeWithLayerMask = 0;
  13274. _this._includeOnlyWithLayerMask = 0;
  13275. _this._lightmapMode = 0;
  13276. _this._excludedMeshesIds = new Array();
  13277. _this._includedOnlyMeshesIds = new Array();
  13278. _this.getScene().addLight(_this);
  13279. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13280. _this._buildUniformLayout();
  13281. _this.includedOnlyMeshes = new Array();
  13282. _this.excludedMeshes = new Array();
  13283. _this._resyncMeshes();
  13284. return _this;
  13285. }
  13286. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13287. /**
  13288. * If every light affecting the material is in this lightmapMode,
  13289. * material.lightmapTexture adds or multiplies
  13290. * (depends on material.useLightmapAsShadowmap)
  13291. * after every other light calculations.
  13292. */
  13293. get: function () {
  13294. return Light._LIGHTMAP_DEFAULT;
  13295. },
  13296. enumerable: true,
  13297. configurable: true
  13298. });
  13299. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13300. /**
  13301. * material.lightmapTexture as only diffuse lighting from this light
  13302. * adds pnly specular lighting from this light
  13303. * adds dynamic shadows
  13304. */
  13305. get: function () {
  13306. return Light._LIGHTMAP_SPECULAR;
  13307. },
  13308. enumerable: true,
  13309. configurable: true
  13310. });
  13311. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13312. /**
  13313. * material.lightmapTexture as only lighting
  13314. * no light calculation from this light
  13315. * only adds dynamic shadows from this light
  13316. */
  13317. get: function () {
  13318. return Light._LIGHTMAP_SHADOWSONLY;
  13319. },
  13320. enumerable: true,
  13321. configurable: true
  13322. });
  13323. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13324. /**
  13325. * Each light type uses the default quantity according to its type:
  13326. * point/spot lights use luminous intensity
  13327. * directional lights use illuminance
  13328. */
  13329. get: function () {
  13330. return Light._INTENSITYMODE_AUTOMATIC;
  13331. },
  13332. enumerable: true,
  13333. configurable: true
  13334. });
  13335. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13336. /**
  13337. * lumen (lm)
  13338. */
  13339. get: function () {
  13340. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13341. },
  13342. enumerable: true,
  13343. configurable: true
  13344. });
  13345. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13346. /**
  13347. * candela (lm/sr)
  13348. */
  13349. get: function () {
  13350. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13351. },
  13352. enumerable: true,
  13353. configurable: true
  13354. });
  13355. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13356. /**
  13357. * lux (lm/m^2)
  13358. */
  13359. get: function () {
  13360. return Light._INTENSITYMODE_ILLUMINANCE;
  13361. },
  13362. enumerable: true,
  13363. configurable: true
  13364. });
  13365. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13366. /**
  13367. * nit (cd/m^2)
  13368. */
  13369. get: function () {
  13370. return Light._INTENSITYMODE_LUMINANCE;
  13371. },
  13372. enumerable: true,
  13373. configurable: true
  13374. });
  13375. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13376. /**
  13377. * Light type const id of the point light.
  13378. */
  13379. get: function () {
  13380. return Light._LIGHTTYPEID_POINTLIGHT;
  13381. },
  13382. enumerable: true,
  13383. configurable: true
  13384. });
  13385. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13386. /**
  13387. * Light type const id of the directional light.
  13388. */
  13389. get: function () {
  13390. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13391. },
  13392. enumerable: true,
  13393. configurable: true
  13394. });
  13395. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13396. /**
  13397. * Light type const id of the spot light.
  13398. */
  13399. get: function () {
  13400. return Light._LIGHTTYPEID_SPOTLIGHT;
  13401. },
  13402. enumerable: true,
  13403. configurable: true
  13404. });
  13405. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13406. /**
  13407. * Light type const id of the hemispheric light.
  13408. */
  13409. get: function () {
  13410. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13411. },
  13412. enumerable: true,
  13413. configurable: true
  13414. });
  13415. Object.defineProperty(Light.prototype, "intensityMode", {
  13416. /**
  13417. * Gets the photometric scale used to interpret the intensity.
  13418. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13419. */
  13420. get: function () {
  13421. return this._intensityMode;
  13422. },
  13423. /**
  13424. * Sets the photometric scale used to interpret the intensity.
  13425. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13426. */
  13427. set: function (value) {
  13428. this._intensityMode = value;
  13429. this._computePhotometricScale();
  13430. },
  13431. enumerable: true,
  13432. configurable: true
  13433. });
  13434. ;
  13435. ;
  13436. Object.defineProperty(Light.prototype, "radius", {
  13437. /**
  13438. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13439. */
  13440. get: function () {
  13441. return this._radius;
  13442. },
  13443. /**
  13444. * sets the light radius used by PBR Materials to simulate soft area lights.
  13445. */
  13446. set: function (value) {
  13447. this._radius = value;
  13448. this._computePhotometricScale();
  13449. },
  13450. enumerable: true,
  13451. configurable: true
  13452. });
  13453. ;
  13454. ;
  13455. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13456. get: function () {
  13457. return this._includedOnlyMeshes;
  13458. },
  13459. set: function (value) {
  13460. this._includedOnlyMeshes = value;
  13461. this._hookArrayForIncludedOnly(value);
  13462. },
  13463. enumerable: true,
  13464. configurable: true
  13465. });
  13466. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13467. get: function () {
  13468. return this._excludedMeshes;
  13469. },
  13470. set: function (value) {
  13471. this._excludedMeshes = value;
  13472. this._hookArrayForExcluded(value);
  13473. },
  13474. enumerable: true,
  13475. configurable: true
  13476. });
  13477. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13478. get: function () {
  13479. return this._excludeWithLayerMask;
  13480. },
  13481. set: function (value) {
  13482. this._excludeWithLayerMask = value;
  13483. this._resyncMeshes();
  13484. },
  13485. enumerable: true,
  13486. configurable: true
  13487. });
  13488. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13489. get: function () {
  13490. return this._includeOnlyWithLayerMask;
  13491. },
  13492. set: function (value) {
  13493. this._includeOnlyWithLayerMask = value;
  13494. this._resyncMeshes();
  13495. },
  13496. enumerable: true,
  13497. configurable: true
  13498. });
  13499. Object.defineProperty(Light.prototype, "lightmapMode", {
  13500. get: function () {
  13501. return this._lightmapMode;
  13502. },
  13503. set: function (value) {
  13504. if (this._lightmapMode === value) {
  13505. return;
  13506. }
  13507. this._lightmapMode = value;
  13508. this._markMeshesAsLightDirty();
  13509. },
  13510. enumerable: true,
  13511. configurable: true
  13512. });
  13513. Light.prototype._buildUniformLayout = function () {
  13514. // Overridden
  13515. };
  13516. /**
  13517. * Returns the string "Light".
  13518. */
  13519. Light.prototype.getClassName = function () {
  13520. return "Light";
  13521. };
  13522. /**
  13523. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13524. */
  13525. Light.prototype.toString = function (fullDetails) {
  13526. var ret = "Name: " + this.name;
  13527. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13528. if (this.animations) {
  13529. for (var i = 0; i < this.animations.length; i++) {
  13530. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13531. }
  13532. }
  13533. if (fullDetails) {
  13534. }
  13535. return ret;
  13536. };
  13537. /**
  13538. * Set the enabled state of this node.
  13539. * @param {boolean} value - the new enabled state
  13540. * @see isEnabled
  13541. */
  13542. Light.prototype.setEnabled = function (value) {
  13543. _super.prototype.setEnabled.call(this, value);
  13544. this._resyncMeshes();
  13545. };
  13546. /**
  13547. * Returns the Light associated shadow generator.
  13548. */
  13549. Light.prototype.getShadowGenerator = function () {
  13550. return this._shadowGenerator;
  13551. };
  13552. /**
  13553. * Returns a Vector3, the absolute light position in the World.
  13554. */
  13555. Light.prototype.getAbsolutePosition = function () {
  13556. return BABYLON.Vector3.Zero();
  13557. };
  13558. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13559. };
  13560. Light.prototype._getWorldMatrix = function () {
  13561. return BABYLON.Matrix.Identity();
  13562. };
  13563. /**
  13564. * Boolean : True if the light will affect the passed mesh.
  13565. */
  13566. Light.prototype.canAffectMesh = function (mesh) {
  13567. if (!mesh) {
  13568. return true;
  13569. }
  13570. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13571. return false;
  13572. }
  13573. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13574. return false;
  13575. }
  13576. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13577. return false;
  13578. }
  13579. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13580. return false;
  13581. }
  13582. return true;
  13583. };
  13584. /**
  13585. * Returns the light World matrix.
  13586. */
  13587. Light.prototype.getWorldMatrix = function () {
  13588. this._currentRenderId = this.getScene().getRenderId();
  13589. var worldMatrix = this._getWorldMatrix();
  13590. if (this.parent && this.parent.getWorldMatrix) {
  13591. if (!this._parentedWorldMatrix) {
  13592. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13593. }
  13594. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13595. this._markSyncedWithParent();
  13596. return this._parentedWorldMatrix;
  13597. }
  13598. return worldMatrix;
  13599. };
  13600. /**
  13601. * Sort function to order lights for rendering.
  13602. * @param a First Light object to compare to second.
  13603. * @param b Second Light object to compare first.
  13604. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13605. */
  13606. Light.compareLightsPriority = function (a, b) {
  13607. //shadow-casting lights have priority over non-shadow-casting lights
  13608. //the renderPrioirty is a secondary sort criterion
  13609. if (a.shadowEnabled !== b.shadowEnabled) {
  13610. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13611. }
  13612. return b.renderPriority - a.renderPriority;
  13613. };
  13614. /**
  13615. * Disposes the light.
  13616. */
  13617. Light.prototype.dispose = function () {
  13618. if (this._shadowGenerator) {
  13619. this._shadowGenerator.dispose();
  13620. this._shadowGenerator = null;
  13621. }
  13622. // Animations
  13623. this.getScene().stopAnimation(this);
  13624. // Remove from meshes
  13625. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13626. var mesh = _a[_i];
  13627. mesh._removeLightSource(this);
  13628. }
  13629. this._uniformBuffer.dispose();
  13630. // Remove from scene
  13631. this.getScene().removeLight(this);
  13632. _super.prototype.dispose.call(this);
  13633. };
  13634. /**
  13635. * Returns the light type ID (integer).
  13636. */
  13637. Light.prototype.getTypeID = function () {
  13638. return 0;
  13639. };
  13640. /**
  13641. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13642. */
  13643. Light.prototype.getScaledIntensity = function () {
  13644. return this._photometricScale * this.intensity;
  13645. };
  13646. /**
  13647. * Returns a new Light object, named "name", from the current one.
  13648. */
  13649. Light.prototype.clone = function (name) {
  13650. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13651. };
  13652. /**
  13653. * Serializes the current light into a Serialization object.
  13654. * Returns the serialized object.
  13655. */
  13656. Light.prototype.serialize = function () {
  13657. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13658. // Type
  13659. serializationObject.type = this.getTypeID();
  13660. // Parent
  13661. if (this.parent) {
  13662. serializationObject.parentId = this.parent.id;
  13663. }
  13664. // Inclusion / exclusions
  13665. if (this.excludedMeshes.length > 0) {
  13666. serializationObject.excludedMeshesIds = [];
  13667. this.excludedMeshes.forEach(function (mesh) {
  13668. serializationObject.excludedMeshesIds.push(mesh.id);
  13669. });
  13670. }
  13671. if (this.includedOnlyMeshes.length > 0) {
  13672. serializationObject.includedOnlyMeshesIds = [];
  13673. this.includedOnlyMeshes.forEach(function (mesh) {
  13674. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13675. });
  13676. }
  13677. // Animations
  13678. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13679. serializationObject.ranges = this.serializeAnimationRanges();
  13680. return serializationObject;
  13681. };
  13682. /**
  13683. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13684. * This new light is named "name" and added to the passed scene.
  13685. */
  13686. Light.GetConstructorFromName = function (type, name, scene) {
  13687. switch (type) {
  13688. case 0:
  13689. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13690. case 1:
  13691. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13692. case 2:
  13693. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13694. case 3:
  13695. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13696. }
  13697. };
  13698. /**
  13699. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13700. */
  13701. Light.Parse = function (parsedLight, scene) {
  13702. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13703. // Inclusion / exclusions
  13704. if (parsedLight.excludedMeshesIds) {
  13705. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13706. }
  13707. if (parsedLight.includedOnlyMeshesIds) {
  13708. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13709. }
  13710. // Parent
  13711. if (parsedLight.parentId) {
  13712. light._waitingParentId = parsedLight.parentId;
  13713. }
  13714. // Animations
  13715. if (parsedLight.animations) {
  13716. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13717. var parsedAnimation = parsedLight.animations[animationIndex];
  13718. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13719. }
  13720. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13721. }
  13722. if (parsedLight.autoAnimate) {
  13723. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13724. }
  13725. return light;
  13726. };
  13727. Light.prototype._hookArrayForExcluded = function (array) {
  13728. var _this = this;
  13729. var oldPush = array.push;
  13730. array.push = function () {
  13731. var items = [];
  13732. for (var _i = 0; _i < arguments.length; _i++) {
  13733. items[_i] = arguments[_i];
  13734. }
  13735. var result = oldPush.apply(array, items);
  13736. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13737. var item = items_1[_a];
  13738. item._resyncLighSource(_this);
  13739. }
  13740. return result;
  13741. };
  13742. var oldSplice = array.splice;
  13743. array.splice = function (index, deleteCount) {
  13744. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13745. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13746. var item = deleted_1[_i];
  13747. item._resyncLighSource(_this);
  13748. }
  13749. return deleted;
  13750. };
  13751. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13752. var item = array_1[_i];
  13753. item._resyncLighSource(this);
  13754. }
  13755. };
  13756. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13757. var _this = this;
  13758. var oldPush = array.push;
  13759. array.push = function () {
  13760. var items = [];
  13761. for (var _i = 0; _i < arguments.length; _i++) {
  13762. items[_i] = arguments[_i];
  13763. }
  13764. var result = oldPush.apply(array, items);
  13765. _this._resyncMeshes();
  13766. return result;
  13767. };
  13768. var oldSplice = array.splice;
  13769. array.splice = function (index, deleteCount) {
  13770. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13771. _this._resyncMeshes();
  13772. return deleted;
  13773. };
  13774. this._resyncMeshes();
  13775. };
  13776. Light.prototype._resyncMeshes = function () {
  13777. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13778. var mesh = _a[_i];
  13779. mesh._resyncLighSource(this);
  13780. }
  13781. };
  13782. Light.prototype._markMeshesAsLightDirty = function () {
  13783. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13784. var mesh = _a[_i];
  13785. if (mesh._lightSources.indexOf(this) !== -1) {
  13786. mesh._markSubMeshesAsLightDirty();
  13787. }
  13788. }
  13789. };
  13790. /**
  13791. * Recomputes the cached photometric scale if needed.
  13792. */
  13793. Light.prototype._computePhotometricScale = function () {
  13794. this._photometricScale = this._getPhotometricScale();
  13795. this.getScene().resetCachedMaterial();
  13796. };
  13797. /**
  13798. * Returns the Photometric Scale according to the light type and intensity mode.
  13799. */
  13800. Light.prototype._getPhotometricScale = function () {
  13801. var photometricScale = 0.0;
  13802. var lightTypeID = this.getTypeID();
  13803. //get photometric mode
  13804. var photometricMode = this.intensityMode;
  13805. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13806. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13807. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13808. }
  13809. else {
  13810. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13811. }
  13812. }
  13813. //compute photometric scale
  13814. switch (lightTypeID) {
  13815. case Light.LIGHTTYPEID_POINTLIGHT:
  13816. case Light.LIGHTTYPEID_SPOTLIGHT:
  13817. switch (photometricMode) {
  13818. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13819. photometricScale = 1.0 / (4.0 * Math.PI);
  13820. break;
  13821. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13822. photometricScale = 1.0;
  13823. break;
  13824. case Light.INTENSITYMODE_LUMINANCE:
  13825. photometricScale = this.radius * this.radius;
  13826. break;
  13827. }
  13828. break;
  13829. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13830. switch (photometricMode) {
  13831. case Light.INTENSITYMODE_ILLUMINANCE:
  13832. photometricScale = 1.0;
  13833. break;
  13834. case Light.INTENSITYMODE_LUMINANCE:
  13835. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13836. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13837. var apexAngleRadians = this.radius;
  13838. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13839. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13840. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13841. photometricScale = solidAngle;
  13842. break;
  13843. }
  13844. break;
  13845. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13846. // No fall off in hemisperic light.
  13847. photometricScale = 1.0;
  13848. break;
  13849. }
  13850. return photometricScale;
  13851. };
  13852. Light.prototype._reorderLightsInScene = function () {
  13853. var scene = this.getScene();
  13854. if (this.renderPriority != 0) {
  13855. scene.requireLightSorting = true;
  13856. }
  13857. this.getScene().sortLightsByPriority();
  13858. };
  13859. return Light;
  13860. }(BABYLON.Node));
  13861. //lightmapMode Consts
  13862. Light._LIGHTMAP_DEFAULT = 0;
  13863. Light._LIGHTMAP_SPECULAR = 1;
  13864. Light._LIGHTMAP_SHADOWSONLY = 2;
  13865. // Intensity Mode Consts
  13866. Light._INTENSITYMODE_AUTOMATIC = 0;
  13867. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13868. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13869. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13870. Light._INTENSITYMODE_LUMINANCE = 4;
  13871. // Light types ids const.
  13872. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13873. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13874. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13875. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13876. __decorate([
  13877. BABYLON.serializeAsColor3()
  13878. ], Light.prototype, "diffuse", void 0);
  13879. __decorate([
  13880. BABYLON.serializeAsColor3()
  13881. ], Light.prototype, "specular", void 0);
  13882. __decorate([
  13883. BABYLON.serialize()
  13884. ], Light.prototype, "intensity", void 0);
  13885. __decorate([
  13886. BABYLON.serialize()
  13887. ], Light.prototype, "range", void 0);
  13888. __decorate([
  13889. BABYLON.serialize()
  13890. ], Light.prototype, "intensityMode", null);
  13891. __decorate([
  13892. BABYLON.serialize()
  13893. ], Light.prototype, "radius", null);
  13894. __decorate([
  13895. BABYLON.serialize()
  13896. ], Light.prototype, "_renderPriority", void 0);
  13897. __decorate([
  13898. BABYLON.expandToProperty("_reorderLightsInScene")
  13899. ], Light.prototype, "renderPriority", void 0);
  13900. __decorate([
  13901. BABYLON.serialize()
  13902. ], Light.prototype, "shadowEnabled", void 0);
  13903. __decorate([
  13904. BABYLON.serialize("excludeWithLayerMask")
  13905. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13906. __decorate([
  13907. BABYLON.serialize("includeOnlyWithLayerMask")
  13908. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13909. __decorate([
  13910. BABYLON.serialize("lightmapMode")
  13911. ], Light.prototype, "_lightmapMode", void 0);
  13912. BABYLON.Light = Light;
  13913. })(BABYLON || (BABYLON = {}));
  13914. //# sourceMappingURL=babylon.light.js.map
  13915. var BABYLON;
  13916. (function (BABYLON) {
  13917. var Camera = (function (_super) {
  13918. __extends(Camera, _super);
  13919. function Camera(name, position, scene) {
  13920. var _this = _super.call(this, name, scene) || this;
  13921. _this.upVector = BABYLON.Vector3.Up();
  13922. _this.orthoLeft = null;
  13923. _this.orthoRight = null;
  13924. _this.orthoBottom = null;
  13925. _this.orthoTop = null;
  13926. _this.fov = 0.8;
  13927. _this.minZ = 1.0;
  13928. _this.maxZ = 10000.0;
  13929. _this.inertia = 0.9;
  13930. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13931. _this.isIntermediate = false;
  13932. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13933. _this.layerMask = 0x0FFFFFFF;
  13934. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13935. // Camera rig members
  13936. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13937. _this._rigCameras = new Array();
  13938. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13939. _this.customRenderTargets = new Array();
  13940. // Cache
  13941. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13942. _this._projectionMatrix = new BABYLON.Matrix();
  13943. _this._doNotComputeProjectionMatrix = false;
  13944. _this._postProcesses = new Array();
  13945. _this._transformMatrix = BABYLON.Matrix.Zero();
  13946. _this._activeMeshes = new BABYLON.SmartArray(256);
  13947. _this._globalPosition = BABYLON.Vector3.Zero();
  13948. _this._refreshFrustumPlanes = true;
  13949. _this.getScene().addCamera(_this);
  13950. if (!_this.getScene().activeCamera) {
  13951. _this.getScene().activeCamera = _this;
  13952. }
  13953. _this.position = position;
  13954. return _this;
  13955. }
  13956. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13957. get: function () {
  13958. return Camera._PERSPECTIVE_CAMERA;
  13959. },
  13960. enumerable: true,
  13961. configurable: true
  13962. });
  13963. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13964. get: function () {
  13965. return Camera._ORTHOGRAPHIC_CAMERA;
  13966. },
  13967. enumerable: true,
  13968. configurable: true
  13969. });
  13970. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13971. get: function () {
  13972. return Camera._FOVMODE_VERTICAL_FIXED;
  13973. },
  13974. enumerable: true,
  13975. configurable: true
  13976. });
  13977. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13978. get: function () {
  13979. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13980. },
  13981. enumerable: true,
  13982. configurable: true
  13983. });
  13984. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13985. get: function () {
  13986. return Camera._RIG_MODE_NONE;
  13987. },
  13988. enumerable: true,
  13989. configurable: true
  13990. });
  13991. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13992. get: function () {
  13993. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13994. },
  13995. enumerable: true,
  13996. configurable: true
  13997. });
  13998. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13999. get: function () {
  14000. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14001. },
  14002. enumerable: true,
  14003. configurable: true
  14004. });
  14005. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14006. get: function () {
  14007. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14008. },
  14009. enumerable: true,
  14010. configurable: true
  14011. });
  14012. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14013. get: function () {
  14014. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14015. },
  14016. enumerable: true,
  14017. configurable: true
  14018. });
  14019. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14020. get: function () {
  14021. return Camera._RIG_MODE_VR;
  14022. },
  14023. enumerable: true,
  14024. configurable: true
  14025. });
  14026. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14027. get: function () {
  14028. return Camera._RIG_MODE_WEBVR;
  14029. },
  14030. enumerable: true,
  14031. configurable: true
  14032. });
  14033. Camera.prototype.getClassName = function () {
  14034. return "Camera";
  14035. };
  14036. /**
  14037. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14038. */
  14039. Camera.prototype.toString = function (fullDetails) {
  14040. var ret = "Name: " + this.name;
  14041. ret += ", type: " + this.getClassName();
  14042. if (this.animations) {
  14043. for (var i = 0; i < this.animations.length; i++) {
  14044. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14045. }
  14046. }
  14047. if (fullDetails) {
  14048. }
  14049. return ret;
  14050. };
  14051. Object.defineProperty(Camera.prototype, "globalPosition", {
  14052. get: function () {
  14053. return this._globalPosition;
  14054. },
  14055. enumerable: true,
  14056. configurable: true
  14057. });
  14058. Camera.prototype.getActiveMeshes = function () {
  14059. return this._activeMeshes;
  14060. };
  14061. Camera.prototype.isActiveMesh = function (mesh) {
  14062. return (this._activeMeshes.indexOf(mesh) !== -1);
  14063. };
  14064. //Cache
  14065. Camera.prototype._initCache = function () {
  14066. _super.prototype._initCache.call(this);
  14067. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14068. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14069. this._cache.mode = undefined;
  14070. this._cache.minZ = undefined;
  14071. this._cache.maxZ = undefined;
  14072. this._cache.fov = undefined;
  14073. this._cache.fovMode = undefined;
  14074. this._cache.aspectRatio = undefined;
  14075. this._cache.orthoLeft = undefined;
  14076. this._cache.orthoRight = undefined;
  14077. this._cache.orthoBottom = undefined;
  14078. this._cache.orthoTop = undefined;
  14079. this._cache.renderWidth = undefined;
  14080. this._cache.renderHeight = undefined;
  14081. };
  14082. Camera.prototype._updateCache = function (ignoreParentClass) {
  14083. if (!ignoreParentClass) {
  14084. _super.prototype._updateCache.call(this);
  14085. }
  14086. var engine = this.getEngine();
  14087. this._cache.position.copyFrom(this.position);
  14088. this._cache.upVector.copyFrom(this.upVector);
  14089. this._cache.mode = this.mode;
  14090. this._cache.minZ = this.minZ;
  14091. this._cache.maxZ = this.maxZ;
  14092. this._cache.fov = this.fov;
  14093. this._cache.fovMode = this.fovMode;
  14094. this._cache.aspectRatio = engine.getAspectRatio(this);
  14095. this._cache.orthoLeft = this.orthoLeft;
  14096. this._cache.orthoRight = this.orthoRight;
  14097. this._cache.orthoBottom = this.orthoBottom;
  14098. this._cache.orthoTop = this.orthoTop;
  14099. this._cache.renderWidth = engine.getRenderWidth();
  14100. this._cache.renderHeight = engine.getRenderHeight();
  14101. };
  14102. Camera.prototype._updateFromScene = function () {
  14103. this.updateCache();
  14104. this.update();
  14105. };
  14106. // Synchronized
  14107. Camera.prototype._isSynchronized = function () {
  14108. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14109. };
  14110. Camera.prototype._isSynchronizedViewMatrix = function () {
  14111. if (!_super.prototype._isSynchronized.call(this))
  14112. return false;
  14113. return this._cache.position.equals(this.position)
  14114. && this._cache.upVector.equals(this.upVector)
  14115. && this.isSynchronizedWithParent();
  14116. };
  14117. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14118. var check = this._cache.mode === this.mode
  14119. && this._cache.minZ === this.minZ
  14120. && this._cache.maxZ === this.maxZ;
  14121. if (!check) {
  14122. return false;
  14123. }
  14124. var engine = this.getEngine();
  14125. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14126. check = this._cache.fov === this.fov
  14127. && this._cache.fovMode === this.fovMode
  14128. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14129. }
  14130. else {
  14131. check = this._cache.orthoLeft === this.orthoLeft
  14132. && this._cache.orthoRight === this.orthoRight
  14133. && this._cache.orthoBottom === this.orthoBottom
  14134. && this._cache.orthoTop === this.orthoTop
  14135. && this._cache.renderWidth === engine.getRenderWidth()
  14136. && this._cache.renderHeight === engine.getRenderHeight();
  14137. }
  14138. return check;
  14139. };
  14140. // Controls
  14141. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14142. };
  14143. Camera.prototype.detachControl = function (element) {
  14144. };
  14145. Camera.prototype.update = function () {
  14146. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14147. this._updateRigCameras();
  14148. }
  14149. this._checkInputs();
  14150. };
  14151. Camera.prototype._checkInputs = function () {
  14152. };
  14153. Object.defineProperty(Camera.prototype, "rigCameras", {
  14154. get: function () {
  14155. return this._rigCameras;
  14156. },
  14157. enumerable: true,
  14158. configurable: true
  14159. });
  14160. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14161. get: function () {
  14162. return this._rigPostProcess;
  14163. },
  14164. enumerable: true,
  14165. configurable: true
  14166. });
  14167. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14168. // invalidate framebuffer
  14169. if (this._postProcesses.length > 0) {
  14170. this._postProcesses[0].markTextureDirty();
  14171. }
  14172. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14173. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14174. var cam = this._rigCameras[i];
  14175. var rigPostProcess = cam._rigPostProcess;
  14176. // for VR rig, there does not have to be a post process
  14177. if (rigPostProcess) {
  14178. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14179. if (isPass) {
  14180. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14181. cam.isIntermediate = this._postProcesses.length === 0;
  14182. }
  14183. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14184. rigPostProcess.markTextureDirty();
  14185. }
  14186. else {
  14187. cam._postProcesses = this._postProcesses.slice(0);
  14188. }
  14189. }
  14190. };
  14191. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14192. if (insertAt === void 0) { insertAt = null; }
  14193. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14194. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14195. return 0;
  14196. }
  14197. if (insertAt == null || insertAt < 0) {
  14198. this._postProcesses.push(postProcess);
  14199. }
  14200. else {
  14201. this._postProcesses.splice(insertAt, 0, postProcess);
  14202. }
  14203. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14204. return this._postProcesses.indexOf(postProcess);
  14205. };
  14206. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14207. if (atIndices === void 0) { atIndices = null; }
  14208. var result = [];
  14209. var i;
  14210. var index;
  14211. if (!atIndices) {
  14212. var idx = this._postProcesses.indexOf(postProcess);
  14213. if (idx !== -1) {
  14214. this._postProcesses.splice(idx, 1);
  14215. }
  14216. }
  14217. else {
  14218. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14219. // iterate descending, so can just splice as we go
  14220. for (i = atIndices.length - 1; i >= 0; i--) {
  14221. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14222. result.push(i);
  14223. continue;
  14224. }
  14225. index = atIndices[i];
  14226. this._postProcesses.splice(index, 1);
  14227. }
  14228. }
  14229. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14230. return result;
  14231. };
  14232. Camera.prototype.getWorldMatrix = function () {
  14233. if (!this._worldMatrix) {
  14234. this._worldMatrix = BABYLON.Matrix.Identity();
  14235. }
  14236. var viewMatrix = this.getViewMatrix();
  14237. viewMatrix.invertToRef(this._worldMatrix);
  14238. return this._worldMatrix;
  14239. };
  14240. Camera.prototype._getViewMatrix = function () {
  14241. return BABYLON.Matrix.Identity();
  14242. };
  14243. Camera.prototype.getViewMatrix = function (force) {
  14244. this._computedViewMatrix = this._computeViewMatrix(force);
  14245. if (!force && this._isSynchronizedViewMatrix()) {
  14246. return this._computedViewMatrix;
  14247. }
  14248. this._refreshFrustumPlanes = true;
  14249. if (!this.parent || !this.parent.getWorldMatrix) {
  14250. this._globalPosition.copyFrom(this.position);
  14251. }
  14252. else {
  14253. if (!this._worldMatrix) {
  14254. this._worldMatrix = BABYLON.Matrix.Identity();
  14255. }
  14256. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14257. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14258. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14259. this._computedViewMatrix.invert();
  14260. this._markSyncedWithParent();
  14261. }
  14262. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14263. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14264. }
  14265. this._currentRenderId = this.getScene().getRenderId();
  14266. return this._computedViewMatrix;
  14267. };
  14268. Camera.prototype._computeViewMatrix = function (force) {
  14269. if (!force && this._isSynchronizedViewMatrix()) {
  14270. return this._computedViewMatrix;
  14271. }
  14272. this._computedViewMatrix = this._getViewMatrix();
  14273. this._currentRenderId = this.getScene().getRenderId();
  14274. return this._computedViewMatrix;
  14275. };
  14276. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14277. this._doNotComputeProjectionMatrix = true;
  14278. if (projection !== undefined) {
  14279. this._projectionMatrix = projection;
  14280. }
  14281. };
  14282. ;
  14283. Camera.prototype.unfreezeProjectionMatrix = function () {
  14284. this._doNotComputeProjectionMatrix = false;
  14285. };
  14286. ;
  14287. Camera.prototype.getProjectionMatrix = function (force) {
  14288. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14289. return this._projectionMatrix;
  14290. }
  14291. this._refreshFrustumPlanes = true;
  14292. var engine = this.getEngine();
  14293. var scene = this.getScene();
  14294. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14295. if (this.minZ <= 0) {
  14296. this.minZ = 0.1;
  14297. }
  14298. if (scene.useRightHandedSystem) {
  14299. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14300. }
  14301. else {
  14302. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14303. }
  14304. return this._projectionMatrix;
  14305. }
  14306. var halfWidth = engine.getRenderWidth() / 2.0;
  14307. var halfHeight = engine.getRenderHeight() / 2.0;
  14308. if (scene.useRightHandedSystem) {
  14309. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14310. }
  14311. else {
  14312. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14313. }
  14314. return this._projectionMatrix;
  14315. };
  14316. Camera.prototype.getTranformationMatrix = function () {
  14317. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14318. return this._transformMatrix;
  14319. };
  14320. Camera.prototype.updateFrustumPlanes = function () {
  14321. if (!this._refreshFrustumPlanes) {
  14322. return;
  14323. }
  14324. this.getTranformationMatrix();
  14325. if (!this._frustumPlanes) {
  14326. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14327. }
  14328. else {
  14329. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14330. }
  14331. this._refreshFrustumPlanes = false;
  14332. };
  14333. Camera.prototype.isInFrustum = function (target) {
  14334. this.updateFrustumPlanes();
  14335. return target.isInFrustum(this._frustumPlanes);
  14336. };
  14337. Camera.prototype.isCompletelyInFrustum = function (target) {
  14338. this.updateFrustumPlanes();
  14339. return target.isCompletelyInFrustum(this._frustumPlanes);
  14340. };
  14341. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14342. if (length === void 0) { length = 100; }
  14343. if (!transform) {
  14344. transform = this.getWorldMatrix();
  14345. }
  14346. if (!origin) {
  14347. origin = this.position;
  14348. }
  14349. var forward = new BABYLON.Vector3(0, 0, 1);
  14350. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14351. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14352. return new BABYLON.Ray(origin, direction, length);
  14353. };
  14354. Camera.prototype.dispose = function () {
  14355. // Animations
  14356. this.getScene().stopAnimation(this);
  14357. // Remove from scene
  14358. this.getScene().removeCamera(this);
  14359. while (this._rigCameras.length > 0) {
  14360. this._rigCameras.pop().dispose();
  14361. }
  14362. // Postprocesses
  14363. var i = this._postProcesses.length;
  14364. while (--i >= 0) {
  14365. this._postProcesses[i].dispose(this);
  14366. }
  14367. _super.prototype.dispose.call(this);
  14368. };
  14369. Object.defineProperty(Camera.prototype, "leftCamera", {
  14370. // ---- Camera rigs section ----
  14371. get: function () {
  14372. if (this._rigCameras.length < 1) {
  14373. return undefined;
  14374. }
  14375. return this._rigCameras[0];
  14376. },
  14377. enumerable: true,
  14378. configurable: true
  14379. });
  14380. Object.defineProperty(Camera.prototype, "rightCamera", {
  14381. get: function () {
  14382. if (this._rigCameras.length < 2) {
  14383. return undefined;
  14384. }
  14385. return this._rigCameras[1];
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. Camera.prototype.getLeftTarget = function () {
  14391. if (this._rigCameras.length < 1) {
  14392. return undefined;
  14393. }
  14394. return this._rigCameras[0].getTarget();
  14395. };
  14396. Camera.prototype.getRightTarget = function () {
  14397. if (this._rigCameras.length < 2) {
  14398. return undefined;
  14399. }
  14400. return this._rigCameras[1].getTarget();
  14401. };
  14402. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14403. while (this._rigCameras.length > 0) {
  14404. this._rigCameras.pop().dispose();
  14405. }
  14406. this.cameraRigMode = mode;
  14407. this._cameraRigParams = {};
  14408. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14409. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14410. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14411. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14412. // create the rig cameras, unless none
  14413. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14414. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14415. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14416. }
  14417. switch (this.cameraRigMode) {
  14418. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14419. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14420. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14421. break;
  14422. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14423. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14424. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14425. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14426. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14427. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14428. break;
  14429. case Camera.RIG_MODE_VR:
  14430. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14431. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14432. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14433. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14434. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14435. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14436. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14437. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14438. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14439. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14440. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14441. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14442. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14443. if (metrics.compensateDistortion) {
  14444. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14445. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14446. }
  14447. break;
  14448. case Camera.RIG_MODE_WEBVR:
  14449. if (rigParams.vrDisplay) {
  14450. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14451. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14452. //Left eye
  14453. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14454. this._rigCameras[0].setCameraRigParameter("left", true);
  14455. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14456. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14457. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14458. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14459. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14460. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14461. this._rigCameras[0].parent = this;
  14462. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14463. //Right eye
  14464. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14465. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14466. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14467. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14468. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14469. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14470. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14471. this._rigCameras[1].parent = this;
  14472. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14473. }
  14474. break;
  14475. }
  14476. this._cascadePostProcessesToRigCams();
  14477. this.
  14478. update();
  14479. };
  14480. Camera.prototype._getVRProjectionMatrix = function () {
  14481. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14482. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14483. return this._projectionMatrix;
  14484. };
  14485. Camera.prototype._updateCameraRotationMatrix = function () {
  14486. //Here for WebVR
  14487. };
  14488. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14489. //Here for WebVR
  14490. };
  14491. /**
  14492. * This function MUST be overwritten by the different WebVR cameras available.
  14493. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14494. */
  14495. Camera.prototype._getWebVRProjectionMatrix = function () {
  14496. return BABYLON.Matrix.Identity();
  14497. };
  14498. /**
  14499. * This function MUST be overwritten by the different WebVR cameras available.
  14500. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14501. */
  14502. Camera.prototype._getWebVRViewMatrix = function () {
  14503. return BABYLON.Matrix.Identity();
  14504. };
  14505. Camera.prototype.setCameraRigParameter = function (name, value) {
  14506. if (!this._cameraRigParams) {
  14507. this._cameraRigParams = {};
  14508. }
  14509. this._cameraRigParams[name] = value;
  14510. //provisionnally:
  14511. if (name === "interaxialDistance") {
  14512. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14513. }
  14514. };
  14515. /**
  14516. * needs to be overridden by children so sub has required properties to be copied
  14517. */
  14518. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14519. return null;
  14520. };
  14521. /**
  14522. * May need to be overridden by children
  14523. */
  14524. Camera.prototype._updateRigCameras = function () {
  14525. for (var i = 0; i < this._rigCameras.length; i++) {
  14526. this._rigCameras[i].minZ = this.minZ;
  14527. this._rigCameras[i].maxZ = this.maxZ;
  14528. this._rigCameras[i].fov = this.fov;
  14529. }
  14530. // only update viewport when ANAGLYPH
  14531. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14532. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14533. }
  14534. };
  14535. Camera.prototype._setupInputs = function () {
  14536. };
  14537. Camera.prototype.serialize = function () {
  14538. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14539. // Type
  14540. serializationObject.type = this.getClassName();
  14541. // Parent
  14542. if (this.parent) {
  14543. serializationObject.parentId = this.parent.id;
  14544. }
  14545. if (this.inputs) {
  14546. this.inputs.serialize(serializationObject);
  14547. }
  14548. // Animations
  14549. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14550. serializationObject.ranges = this.serializeAnimationRanges();
  14551. return serializationObject;
  14552. };
  14553. Camera.prototype.clone = function (name) {
  14554. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14555. };
  14556. Camera.prototype.getDirection = function (localAxis) {
  14557. var result = BABYLON.Vector3.Zero();
  14558. this.getDirectionToRef(localAxis, result);
  14559. return result;
  14560. };
  14561. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14562. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14563. };
  14564. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14565. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14566. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14567. switch (type) {
  14568. case "ArcRotateCamera":
  14569. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14570. case "DeviceOrientationCamera":
  14571. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14572. case "FollowCamera":
  14573. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14574. case "ArcFollowCamera":
  14575. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14576. case "GamepadCamera":
  14577. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14578. case "TouchCamera":
  14579. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14580. case "VirtualJoysticksCamera":
  14581. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14582. case "WebVRFreeCamera":
  14583. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14584. case "WebVRGamepadCamera":
  14585. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14586. case "VRDeviceOrientationFreeCamera":
  14587. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14588. case "VRDeviceOrientationGamepadCamera":
  14589. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14590. case "AnaglyphArcRotateCamera":
  14591. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14592. case "AnaglyphFreeCamera":
  14593. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14594. case "AnaglyphGamepadCamera":
  14595. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14596. case "AnaglyphUniversalCamera":
  14597. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14598. case "StereoscopicArcRotateCamera":
  14599. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14600. case "StereoscopicFreeCamera":
  14601. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14602. case "StereoscopicGamepadCamera":
  14603. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14604. case "StereoscopicUniversalCamera":
  14605. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14606. case "FreeCamera":
  14607. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14608. default:
  14609. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14610. }
  14611. };
  14612. Camera.Parse = function (parsedCamera, scene) {
  14613. var type = parsedCamera.type;
  14614. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14615. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14616. // Parent
  14617. if (parsedCamera.parentId) {
  14618. camera._waitingParentId = parsedCamera.parentId;
  14619. }
  14620. //If camera has an input manager, let it parse inputs settings
  14621. if (camera.inputs) {
  14622. camera.inputs.parse(parsedCamera);
  14623. camera._setupInputs();
  14624. }
  14625. if (camera.setPosition) {
  14626. camera.position.copyFromFloats(0, 0, 0);
  14627. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14628. }
  14629. // Target
  14630. if (parsedCamera.target) {
  14631. if (camera.setTarget) {
  14632. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14633. }
  14634. }
  14635. // Apply 3d rig, when found
  14636. if (parsedCamera.cameraRigMode) {
  14637. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14638. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14639. }
  14640. // Animations
  14641. if (parsedCamera.animations) {
  14642. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14643. var parsedAnimation = parsedCamera.animations[animationIndex];
  14644. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14645. }
  14646. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14647. }
  14648. if (parsedCamera.autoAnimate) {
  14649. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14650. }
  14651. return camera;
  14652. };
  14653. return Camera;
  14654. }(BABYLON.Node));
  14655. // Statics
  14656. Camera._PERSPECTIVE_CAMERA = 0;
  14657. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14658. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14659. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14660. Camera._RIG_MODE_NONE = 0;
  14661. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14662. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14663. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14664. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14665. Camera._RIG_MODE_VR = 20;
  14666. Camera._RIG_MODE_WEBVR = 21;
  14667. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14668. __decorate([
  14669. BABYLON.serializeAsVector3()
  14670. ], Camera.prototype, "position", void 0);
  14671. __decorate([
  14672. BABYLON.serializeAsVector3()
  14673. ], Camera.prototype, "upVector", void 0);
  14674. __decorate([
  14675. BABYLON.serialize()
  14676. ], Camera.prototype, "orthoLeft", void 0);
  14677. __decorate([
  14678. BABYLON.serialize()
  14679. ], Camera.prototype, "orthoRight", void 0);
  14680. __decorate([
  14681. BABYLON.serialize()
  14682. ], Camera.prototype, "orthoBottom", void 0);
  14683. __decorate([
  14684. BABYLON.serialize()
  14685. ], Camera.prototype, "orthoTop", void 0);
  14686. __decorate([
  14687. BABYLON.serialize()
  14688. ], Camera.prototype, "fov", void 0);
  14689. __decorate([
  14690. BABYLON.serialize()
  14691. ], Camera.prototype, "minZ", void 0);
  14692. __decorate([
  14693. BABYLON.serialize()
  14694. ], Camera.prototype, "maxZ", void 0);
  14695. __decorate([
  14696. BABYLON.serialize()
  14697. ], Camera.prototype, "inertia", void 0);
  14698. __decorate([
  14699. BABYLON.serialize()
  14700. ], Camera.prototype, "mode", void 0);
  14701. __decorate([
  14702. BABYLON.serialize()
  14703. ], Camera.prototype, "layerMask", void 0);
  14704. __decorate([
  14705. BABYLON.serialize()
  14706. ], Camera.prototype, "fovMode", void 0);
  14707. __decorate([
  14708. BABYLON.serialize()
  14709. ], Camera.prototype, "cameraRigMode", void 0);
  14710. __decorate([
  14711. BABYLON.serialize()
  14712. ], Camera.prototype, "interaxialDistance", void 0);
  14713. __decorate([
  14714. BABYLON.serialize()
  14715. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14716. BABYLON.Camera = Camera;
  14717. })(BABYLON || (BABYLON = {}));
  14718. //# sourceMappingURL=babylon.camera.js.map
  14719. var BABYLON;
  14720. (function (BABYLON) {
  14721. var RenderingManager = (function () {
  14722. function RenderingManager(scene) {
  14723. this._renderingGroups = new Array();
  14724. this._autoClearDepthStencil = {};
  14725. this._customOpaqueSortCompareFn = {};
  14726. this._customAlphaTestSortCompareFn = {};
  14727. this._customTransparentSortCompareFn = {};
  14728. this._renderinGroupInfo = null;
  14729. this._scene = scene;
  14730. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14731. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14732. }
  14733. }
  14734. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14735. if (depth === void 0) { depth = true; }
  14736. if (stencil === void 0) { stencil = true; }
  14737. if (this._depthStencilBufferAlreadyCleaned) {
  14738. return;
  14739. }
  14740. this._scene.getEngine().clear(null, false, depth, stencil);
  14741. this._depthStencilBufferAlreadyCleaned = true;
  14742. };
  14743. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14744. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14745. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14746. var info = null;
  14747. if (observable) {
  14748. if (!this._renderinGroupInfo) {
  14749. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14750. }
  14751. info = this._renderinGroupInfo;
  14752. info.scene = this._scene;
  14753. info.camera = this._scene.activeCamera;
  14754. }
  14755. // Dispatch sprites
  14756. if (renderSprites) {
  14757. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14758. var manager = this._scene.spriteManagers[index];
  14759. this.dispatchSprites(manager);
  14760. }
  14761. }
  14762. // Render
  14763. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14764. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14765. var renderingGroup = this._renderingGroups[index];
  14766. if (!renderingGroup && !observable)
  14767. continue;
  14768. this._currentIndex = index;
  14769. var renderingGroupMask = 0;
  14770. // Fire PRECLEAR stage
  14771. if (observable) {
  14772. renderingGroupMask = Math.pow(2, index);
  14773. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14774. info.renderingGroupId = index;
  14775. observable.notifyObservers(info, renderingGroupMask);
  14776. }
  14777. // Clear depth/stencil if needed
  14778. if (RenderingManager.AUTOCLEAR) {
  14779. var autoClear = this._autoClearDepthStencil[index];
  14780. if (autoClear && autoClear.autoClear) {
  14781. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14782. }
  14783. }
  14784. if (observable) {
  14785. // Fire PREOPAQUE stage
  14786. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14787. observable.notifyObservers(info, renderingGroupMask);
  14788. // Fire PRETRANSPARENT stage
  14789. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14790. observable.notifyObservers(info, renderingGroupMask);
  14791. }
  14792. if (renderingGroup)
  14793. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14794. // Fire POSTTRANSPARENT stage
  14795. if (observable) {
  14796. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14797. observable.notifyObservers(info, renderingGroupMask);
  14798. }
  14799. }
  14800. };
  14801. RenderingManager.prototype.reset = function () {
  14802. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14803. var renderingGroup = this._renderingGroups[index];
  14804. if (renderingGroup) {
  14805. renderingGroup.prepare();
  14806. }
  14807. }
  14808. };
  14809. RenderingManager.prototype.dispose = function () {
  14810. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14811. var renderingGroup = this._renderingGroups[index];
  14812. if (renderingGroup) {
  14813. renderingGroup.dispose();
  14814. }
  14815. }
  14816. this._renderingGroups.length = 0;
  14817. };
  14818. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14819. if (!this._renderingGroups[renderingGroupId]) {
  14820. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14821. }
  14822. };
  14823. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14824. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14825. this._prepareRenderingGroup(renderingGroupId);
  14826. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14827. };
  14828. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14829. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14830. this._prepareRenderingGroup(renderingGroupId);
  14831. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14832. };
  14833. RenderingManager.prototype.dispatch = function (subMesh) {
  14834. var mesh = subMesh.getMesh();
  14835. var renderingGroupId = mesh.renderingGroupId || 0;
  14836. this._prepareRenderingGroup(renderingGroupId);
  14837. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14838. };
  14839. /**
  14840. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14841. * This allowed control for front to back rendering or reversly depending of the special needs.
  14842. *
  14843. * @param renderingGroupId The rendering group id corresponding to its index
  14844. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14845. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14846. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14847. */
  14848. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14849. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14850. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14851. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14852. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14853. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14854. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14855. if (this._renderingGroups[renderingGroupId]) {
  14856. var group = this._renderingGroups[renderingGroupId];
  14857. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14858. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14859. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14860. }
  14861. };
  14862. /**
  14863. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14864. *
  14865. * @param renderingGroupId The rendering group id corresponding to its index
  14866. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14867. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14868. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14869. */
  14870. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14871. if (depth === void 0) { depth = true; }
  14872. if (stencil === void 0) { stencil = true; }
  14873. this._autoClearDepthStencil[renderingGroupId] = {
  14874. autoClear: autoClearDepthStencil,
  14875. depth: depth,
  14876. stencil: stencil
  14877. };
  14878. };
  14879. return RenderingManager;
  14880. }());
  14881. /**
  14882. * The max id used for rendering groups (not included)
  14883. */
  14884. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14885. /**
  14886. * The min id used for rendering groups (included)
  14887. */
  14888. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14889. /**
  14890. * Used to globally prevent autoclearing scenes.
  14891. */
  14892. RenderingManager.AUTOCLEAR = true;
  14893. BABYLON.RenderingManager = RenderingManager;
  14894. })(BABYLON || (BABYLON = {}));
  14895. //# sourceMappingURL=babylon.renderingManager.js.map
  14896. var BABYLON;
  14897. (function (BABYLON) {
  14898. var RenderingGroup = (function () {
  14899. /**
  14900. * Creates a new rendering group.
  14901. * @param index The rendering group index
  14902. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14903. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14904. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14905. */
  14906. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14907. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14908. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14909. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14910. this.index = index;
  14911. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14912. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14913. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14914. this._particleSystems = new BABYLON.SmartArray(256);
  14915. this._spriteManagers = new BABYLON.SmartArray(256);
  14916. this._edgesRenderers = new BABYLON.SmartArray(16);
  14917. this._scene = scene;
  14918. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14919. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14920. this.transparentSortCompareFn = transparentSortCompareFn;
  14921. }
  14922. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14923. /**
  14924. * Set the opaque sort comparison function.
  14925. * If null the sub meshes will be render in the order they were created
  14926. */
  14927. set: function (value) {
  14928. this._opaqueSortCompareFn = value;
  14929. if (value) {
  14930. this._renderOpaque = this.renderOpaqueSorted;
  14931. }
  14932. else {
  14933. this._renderOpaque = RenderingGroup.renderUnsorted;
  14934. }
  14935. },
  14936. enumerable: true,
  14937. configurable: true
  14938. });
  14939. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14940. /**
  14941. * Set the alpha test sort comparison function.
  14942. * If null the sub meshes will be render in the order they were created
  14943. */
  14944. set: function (value) {
  14945. this._alphaTestSortCompareFn = value;
  14946. if (value) {
  14947. this._renderAlphaTest = this.renderAlphaTestSorted;
  14948. }
  14949. else {
  14950. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14951. }
  14952. },
  14953. enumerable: true,
  14954. configurable: true
  14955. });
  14956. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14957. /**
  14958. * Set the transparent sort comparison function.
  14959. * If null the sub meshes will be render in the order they were created
  14960. */
  14961. set: function (value) {
  14962. if (value) {
  14963. this._transparentSortCompareFn = value;
  14964. }
  14965. else {
  14966. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14967. }
  14968. this._renderTransparent = this.renderTransparentSorted;
  14969. },
  14970. enumerable: true,
  14971. configurable: true
  14972. });
  14973. /**
  14974. * Render all the sub meshes contained in the group.
  14975. * @param customRenderFunction Used to override the default render behaviour of the group.
  14976. * @returns true if rendered some submeshes.
  14977. */
  14978. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14979. if (customRenderFunction) {
  14980. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14981. return;
  14982. }
  14983. var engine = this._scene.getEngine();
  14984. // Opaque
  14985. if (this._opaqueSubMeshes.length !== 0) {
  14986. this._renderOpaque(this._opaqueSubMeshes);
  14987. }
  14988. // Alpha test
  14989. if (this._alphaTestSubMeshes.length !== 0) {
  14990. engine.setAlphaTesting(true);
  14991. this._renderAlphaTest(this._alphaTestSubMeshes);
  14992. engine.setAlphaTesting(false);
  14993. }
  14994. var stencilState = engine.getStencilBuffer();
  14995. engine.setStencilBuffer(false);
  14996. // Sprites
  14997. if (renderSprites) {
  14998. this._renderSprites();
  14999. }
  15000. // Particles
  15001. if (renderParticles) {
  15002. this._renderParticles(activeMeshes);
  15003. }
  15004. if (this.onBeforeTransparentRendering) {
  15005. this.onBeforeTransparentRendering();
  15006. }
  15007. // Transparent
  15008. if (this._transparentSubMeshes.length !== 0) {
  15009. this._renderTransparent(this._transparentSubMeshes);
  15010. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15011. }
  15012. engine.setStencilBuffer(stencilState);
  15013. // Edges
  15014. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15015. this._edgesRenderers.data[edgesRendererIndex].render();
  15016. }
  15017. };
  15018. /**
  15019. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15020. * @param subMeshes The submeshes to render
  15021. */
  15022. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15023. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15024. };
  15025. /**
  15026. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15027. * @param subMeshes The submeshes to render
  15028. */
  15029. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15030. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15031. };
  15032. /**
  15033. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15034. * @param subMeshes The submeshes to render
  15035. */
  15036. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15037. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15038. };
  15039. /**
  15040. * Renders the submeshes in a specified order.
  15041. * @param subMeshes The submeshes to sort before render
  15042. * @param sortCompareFn The comparison function use to sort
  15043. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15044. * @param transparent Specifies to activate blending if true
  15045. */
  15046. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15047. var subIndex = 0;
  15048. var subMesh;
  15049. for (; subIndex < subMeshes.length; subIndex++) {
  15050. subMesh = subMeshes.data[subIndex];
  15051. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15052. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15053. }
  15054. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15055. sortedArray.sort(sortCompareFn);
  15056. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15057. subMesh = sortedArray[subIndex];
  15058. subMesh.render(transparent);
  15059. }
  15060. };
  15061. /**
  15062. * Renders the submeshes in the order they were dispatched (no sort applied).
  15063. * @param subMeshes The submeshes to render
  15064. */
  15065. RenderingGroup.renderUnsorted = function (subMeshes) {
  15066. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15067. var submesh = subMeshes.data[subIndex];
  15068. submesh.render(false);
  15069. }
  15070. };
  15071. /**
  15072. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15073. * are rendered back to front if in the same alpha index.
  15074. *
  15075. * @param a The first submesh
  15076. * @param b The second submesh
  15077. * @returns The result of the comparison
  15078. */
  15079. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15080. // Alpha index first
  15081. if (a._alphaIndex > b._alphaIndex) {
  15082. return 1;
  15083. }
  15084. if (a._alphaIndex < b._alphaIndex) {
  15085. return -1;
  15086. }
  15087. // Then distance to camera
  15088. return RenderingGroup.backToFrontSortCompare(a, b);
  15089. };
  15090. /**
  15091. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15092. * are rendered back to front.
  15093. *
  15094. * @param a The first submesh
  15095. * @param b The second submesh
  15096. * @returns The result of the comparison
  15097. */
  15098. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15099. // Then distance to camera
  15100. if (a._distanceToCamera < b._distanceToCamera) {
  15101. return 1;
  15102. }
  15103. if (a._distanceToCamera > b._distanceToCamera) {
  15104. return -1;
  15105. }
  15106. return 0;
  15107. };
  15108. /**
  15109. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15110. * are rendered front to back (prevent overdraw).
  15111. *
  15112. * @param a The first submesh
  15113. * @param b The second submesh
  15114. * @returns The result of the comparison
  15115. */
  15116. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15117. // Then distance to camera
  15118. if (a._distanceToCamera < b._distanceToCamera) {
  15119. return -1;
  15120. }
  15121. if (a._distanceToCamera > b._distanceToCamera) {
  15122. return 1;
  15123. }
  15124. return 0;
  15125. };
  15126. /**
  15127. * Resets the different lists of submeshes to prepare a new frame.
  15128. */
  15129. RenderingGroup.prototype.prepare = function () {
  15130. this._opaqueSubMeshes.reset();
  15131. this._transparentSubMeshes.reset();
  15132. this._alphaTestSubMeshes.reset();
  15133. this._particleSystems.reset();
  15134. this._spriteManagers.reset();
  15135. this._edgesRenderers.reset();
  15136. };
  15137. RenderingGroup.prototype.dispose = function () {
  15138. this._opaqueSubMeshes.dispose();
  15139. this._transparentSubMeshes.dispose();
  15140. this._alphaTestSubMeshes.dispose();
  15141. this._particleSystems.dispose();
  15142. this._spriteManagers.dispose();
  15143. this._edgesRenderers.dispose();
  15144. };
  15145. /**
  15146. * Inserts the submesh in its correct queue depending on its material.
  15147. * @param subMesh The submesh to dispatch
  15148. */
  15149. RenderingGroup.prototype.dispatch = function (subMesh) {
  15150. var material = subMesh.getMaterial();
  15151. var mesh = subMesh.getMesh();
  15152. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15153. this._transparentSubMeshes.push(subMesh);
  15154. }
  15155. else if (material.needAlphaTesting()) {
  15156. this._alphaTestSubMeshes.push(subMesh);
  15157. }
  15158. else {
  15159. this._opaqueSubMeshes.push(subMesh); // Opaque
  15160. }
  15161. if (mesh._edgesRenderer) {
  15162. this._edgesRenderers.push(mesh._edgesRenderer);
  15163. }
  15164. };
  15165. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15166. this._spriteManagers.push(spriteManager);
  15167. };
  15168. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15169. this._particleSystems.push(particleSystem);
  15170. };
  15171. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15172. if (this._particleSystems.length === 0) {
  15173. return;
  15174. }
  15175. // Particles
  15176. var activeCamera = this._scene.activeCamera;
  15177. this._scene._particlesDuration.beginMonitoring();
  15178. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15179. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15180. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15181. continue;
  15182. }
  15183. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15184. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15185. }
  15186. }
  15187. this._scene._particlesDuration.endMonitoring(false);
  15188. };
  15189. RenderingGroup.prototype._renderSprites = function () {
  15190. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15191. return;
  15192. }
  15193. // Sprites
  15194. var activeCamera = this._scene.activeCamera;
  15195. this._scene._spritesDuration.beginMonitoring();
  15196. for (var id = 0; id < this._spriteManagers.length; id++) {
  15197. var spriteManager = this._spriteManagers.data[id];
  15198. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15199. spriteManager.render();
  15200. }
  15201. }
  15202. this._scene._spritesDuration.endMonitoring(false);
  15203. };
  15204. return RenderingGroup;
  15205. }());
  15206. BABYLON.RenderingGroup = RenderingGroup;
  15207. })(BABYLON || (BABYLON = {}));
  15208. //# sourceMappingURL=babylon.renderingGroup.js.map
  15209. var BABYLON;
  15210. (function (BABYLON) {
  15211. var ClickInfo = (function () {
  15212. function ClickInfo() {
  15213. this._singleClick = false;
  15214. this._doubleClick = false;
  15215. this._hasSwiped = false;
  15216. this._ignore = false;
  15217. }
  15218. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15219. get: function () {
  15220. return this._singleClick;
  15221. },
  15222. set: function (b) {
  15223. this._singleClick = b;
  15224. },
  15225. enumerable: true,
  15226. configurable: true
  15227. });
  15228. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15229. get: function () {
  15230. return this._doubleClick;
  15231. },
  15232. set: function (b) {
  15233. this._doubleClick = b;
  15234. },
  15235. enumerable: true,
  15236. configurable: true
  15237. });
  15238. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15239. get: function () {
  15240. return this._hasSwiped;
  15241. },
  15242. set: function (b) {
  15243. this._hasSwiped = b;
  15244. },
  15245. enumerable: true,
  15246. configurable: true
  15247. });
  15248. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15249. get: function () {
  15250. return this._ignore;
  15251. },
  15252. set: function (b) {
  15253. this._ignore = b;
  15254. },
  15255. enumerable: true,
  15256. configurable: true
  15257. });
  15258. return ClickInfo;
  15259. }());
  15260. var PointerEventTypes = (function () {
  15261. function PointerEventTypes() {
  15262. }
  15263. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15264. get: function () {
  15265. return PointerEventTypes._POINTERDOWN;
  15266. },
  15267. enumerable: true,
  15268. configurable: true
  15269. });
  15270. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15271. get: function () {
  15272. return PointerEventTypes._POINTERUP;
  15273. },
  15274. enumerable: true,
  15275. configurable: true
  15276. });
  15277. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15278. get: function () {
  15279. return PointerEventTypes._POINTERMOVE;
  15280. },
  15281. enumerable: true,
  15282. configurable: true
  15283. });
  15284. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15285. get: function () {
  15286. return PointerEventTypes._POINTERWHEEL;
  15287. },
  15288. enumerable: true,
  15289. configurable: true
  15290. });
  15291. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15292. get: function () {
  15293. return PointerEventTypes._POINTERPICK;
  15294. },
  15295. enumerable: true,
  15296. configurable: true
  15297. });
  15298. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15299. get: function () {
  15300. return PointerEventTypes._POINTERTAP;
  15301. },
  15302. enumerable: true,
  15303. configurable: true
  15304. });
  15305. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15306. get: function () {
  15307. return PointerEventTypes._POINTERDOUBLETAP;
  15308. },
  15309. enumerable: true,
  15310. configurable: true
  15311. });
  15312. return PointerEventTypes;
  15313. }());
  15314. PointerEventTypes._POINTERDOWN = 0x01;
  15315. PointerEventTypes._POINTERUP = 0x02;
  15316. PointerEventTypes._POINTERMOVE = 0x04;
  15317. PointerEventTypes._POINTERWHEEL = 0x08;
  15318. PointerEventTypes._POINTERPICK = 0x10;
  15319. PointerEventTypes._POINTERTAP = 0x20;
  15320. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15321. BABYLON.PointerEventTypes = PointerEventTypes;
  15322. var PointerInfoBase = (function () {
  15323. function PointerInfoBase(type, event) {
  15324. this.type = type;
  15325. this.event = event;
  15326. }
  15327. return PointerInfoBase;
  15328. }());
  15329. BABYLON.PointerInfoBase = PointerInfoBase;
  15330. /**
  15331. * This class is used to store pointer related info for the onPrePointerObservable event.
  15332. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15333. */
  15334. var PointerInfoPre = (function (_super) {
  15335. __extends(PointerInfoPre, _super);
  15336. function PointerInfoPre(type, event, localX, localY) {
  15337. var _this = _super.call(this, type, event) || this;
  15338. _this.skipOnPointerObservable = false;
  15339. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15340. return _this;
  15341. }
  15342. return PointerInfoPre;
  15343. }(PointerInfoBase));
  15344. BABYLON.PointerInfoPre = PointerInfoPre;
  15345. /**
  15346. * This type contains all the data related to a pointer event in Babylon.js.
  15347. * 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.
  15348. */
  15349. var PointerInfo = (function (_super) {
  15350. __extends(PointerInfo, _super);
  15351. function PointerInfo(type, event, pickInfo) {
  15352. var _this = _super.call(this, type, event) || this;
  15353. _this.pickInfo = pickInfo;
  15354. return _this;
  15355. }
  15356. return PointerInfo;
  15357. }(PointerInfoBase));
  15358. BABYLON.PointerInfo = PointerInfo;
  15359. /**
  15360. * This class is used by the onRenderingGroupObservable
  15361. */
  15362. var RenderingGroupInfo = (function () {
  15363. function RenderingGroupInfo() {
  15364. }
  15365. return RenderingGroupInfo;
  15366. }());
  15367. /**
  15368. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15369. * This stage will be fired no matter what
  15370. */
  15371. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15372. /**
  15373. * Called before opaque object are rendered.
  15374. * This stage will be fired only if there's 3D Opaque content to render
  15375. */
  15376. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15377. /**
  15378. * Called after the opaque objects are rendered and before the transparent ones
  15379. * This stage will be fired only if there's 3D transparent content to render
  15380. */
  15381. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15382. /**
  15383. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15384. * This stage will be fired no matter what
  15385. */
  15386. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15387. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15388. /**
  15389. * Represents a scene to be rendered by the engine.
  15390. * @see http://doc.babylonjs.com/page.php?p=21911
  15391. */
  15392. var Scene = (function () {
  15393. /**
  15394. * @constructor
  15395. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15396. */
  15397. function Scene(engine) {
  15398. // Members
  15399. this.autoClear = true;
  15400. this.autoClearDepthAndStencil = true;
  15401. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15402. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15403. this.forceWireframe = false;
  15404. this._forcePointsCloud = false;
  15405. this.forceShowBoundingBoxes = false;
  15406. this.animationsEnabled = true;
  15407. this.constantlyUpdateMeshUnderPointer = false;
  15408. this.hoverCursor = "pointer";
  15409. // Metadata
  15410. this.metadata = null;
  15411. // Events
  15412. /**
  15413. * An event triggered when the scene is disposed.
  15414. * @type {BABYLON.Observable}
  15415. */
  15416. this.onDisposeObservable = new BABYLON.Observable();
  15417. /**
  15418. * An event triggered before rendering the scene
  15419. * @type {BABYLON.Observable}
  15420. */
  15421. this.onBeforeRenderObservable = new BABYLON.Observable();
  15422. /**
  15423. * An event triggered after rendering the scene
  15424. * @type {BABYLON.Observable}
  15425. */
  15426. this.onAfterRenderObservable = new BABYLON.Observable();
  15427. /**
  15428. * An event triggered when the scene is ready
  15429. * @type {BABYLON.Observable}
  15430. */
  15431. this.onReadyObservable = new BABYLON.Observable();
  15432. /**
  15433. * An event triggered before rendering a camera
  15434. * @type {BABYLON.Observable}
  15435. */
  15436. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15437. /**
  15438. * An event triggered after rendering a camera
  15439. * @type {BABYLON.Observable}
  15440. */
  15441. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15442. /**
  15443. * An event triggered when a camera is created
  15444. * @type {BABYLON.Observable}
  15445. */
  15446. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15447. /**
  15448. * An event triggered when a camera is removed
  15449. * @type {BABYLON.Observable}
  15450. */
  15451. this.onCameraRemovedObservable = new BABYLON.Observable();
  15452. /**
  15453. * An event triggered when a light is created
  15454. * @type {BABYLON.Observable}
  15455. */
  15456. this.onNewLightAddedObservable = new BABYLON.Observable();
  15457. /**
  15458. * An event triggered when a light is removed
  15459. * @type {BABYLON.Observable}
  15460. */
  15461. this.onLightRemovedObservable = new BABYLON.Observable();
  15462. /**
  15463. * An event triggered when a geometry is created
  15464. * @type {BABYLON.Observable}
  15465. */
  15466. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15467. /**
  15468. * An event triggered when a geometry is removed
  15469. * @type {BABYLON.Observable}
  15470. */
  15471. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15472. /**
  15473. * An event triggered when a mesh is created
  15474. * @type {BABYLON.Observable}
  15475. */
  15476. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15477. /**
  15478. * An event triggered when a mesh is removed
  15479. * @type {BABYLON.Observable}
  15480. */
  15481. this.onMeshRemovedObservable = new BABYLON.Observable();
  15482. /**
  15483. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15484. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15485. * 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)
  15486. */
  15487. this.onRenderingGroupObservable = new BABYLON.Observable();
  15488. // Animations
  15489. this.animations = [];
  15490. /**
  15491. * 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).
  15492. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15493. */
  15494. this.onPrePointerObservable = new BABYLON.Observable();
  15495. /**
  15496. * Observable event triggered each time an input event is received from the rendering canvas
  15497. */
  15498. this.onPointerObservable = new BABYLON.Observable();
  15499. this._meshPickProceed = false;
  15500. this._previousHasSwiped = false;
  15501. this._currentPickResult = null;
  15502. this._previousPickResult = null;
  15503. this._isButtonPressed = false;
  15504. this._doubleClickOccured = false;
  15505. 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
  15506. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15507. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15508. this._startingPointerTime = 0;
  15509. this._previousStartingPointerTime = 0;
  15510. // Coordinate system
  15511. /**
  15512. * use right-handed coordinate system on this scene.
  15513. * @type {boolean}
  15514. */
  15515. this._useRightHandedSystem = false;
  15516. // Fog
  15517. /**
  15518. * is fog enabled on this scene.
  15519. * @type {boolean}
  15520. */
  15521. this._fogEnabled = true;
  15522. this._fogMode = Scene.FOGMODE_NONE;
  15523. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15524. this.fogDensity = 0.1;
  15525. this.fogStart = 0;
  15526. this.fogEnd = 1000.0;
  15527. // Lights
  15528. /**
  15529. * is shadow enabled on this scene.
  15530. * @type {boolean}
  15531. */
  15532. this._shadowsEnabled = true;
  15533. /**
  15534. * is light enabled on this scene.
  15535. * @type {boolean}
  15536. */
  15537. this._lightsEnabled = true;
  15538. /**
  15539. * All of the lights added to this scene.
  15540. * @see BABYLON.Light
  15541. * @type {BABYLON.Light[]}
  15542. */
  15543. this.lights = new Array();
  15544. // Cameras
  15545. /**
  15546. * All of the cameras added to this scene.
  15547. * @see BABYLON.Camera
  15548. * @type {BABYLON.Camera[]}
  15549. */
  15550. this.cameras = new Array();
  15551. this.activeCameras = new Array();
  15552. // Meshes
  15553. /**
  15554. * All of the (abstract) meshes added to this scene.
  15555. * @see BABYLON.AbstractMesh
  15556. * @type {BABYLON.AbstractMesh[]}
  15557. */
  15558. this.meshes = new Array();
  15559. // Geometries
  15560. this._geometries = new Array();
  15561. this.materials = new Array();
  15562. this.multiMaterials = new Array();
  15563. // Textures
  15564. this._texturesEnabled = true;
  15565. this.textures = new Array();
  15566. // Particles
  15567. this.particlesEnabled = true;
  15568. this.particleSystems = new Array();
  15569. // Sprites
  15570. this.spritesEnabled = true;
  15571. this.spriteManagers = new Array();
  15572. // Layers
  15573. this.layers = new Array();
  15574. this.highlightLayers = new Array();
  15575. // Skeletons
  15576. this._skeletonsEnabled = true;
  15577. this.skeletons = new Array();
  15578. // Morph targets
  15579. this.morphTargetManagers = new Array();
  15580. // Lens flares
  15581. this.lensFlaresEnabled = true;
  15582. this.lensFlareSystems = new Array();
  15583. // Collisions
  15584. this.collisionsEnabled = true;
  15585. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15586. // Postprocesses
  15587. this.postProcessesEnabled = true;
  15588. // Customs render targets
  15589. this.renderTargetsEnabled = true;
  15590. this.dumpNextRenderTargets = false;
  15591. this.customRenderTargets = new Array();
  15592. // Imported meshes
  15593. this.importedMeshesFiles = new Array();
  15594. // Probes
  15595. this.probesEnabled = true;
  15596. this.reflectionProbes = new Array();
  15597. this._actionManagers = new Array();
  15598. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15599. // Procedural textures
  15600. this.proceduralTexturesEnabled = true;
  15601. this._proceduralTextures = new Array();
  15602. this.soundTracks = new Array();
  15603. this._audioEnabled = true;
  15604. this._headphone = false;
  15605. // Performance counters
  15606. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15607. this._totalLightsCounter = new BABYLON.PerfCounter();
  15608. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15609. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15610. this._totalVertices = new BABYLON.PerfCounter();
  15611. this._activeIndices = new BABYLON.PerfCounter();
  15612. this._activeParticles = new BABYLON.PerfCounter();
  15613. this._lastFrameDuration = new BABYLON.PerfCounter();
  15614. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15615. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15616. this._particlesDuration = new BABYLON.PerfCounter();
  15617. this._renderDuration = new BABYLON.PerfCounter();
  15618. this._spritesDuration = new BABYLON.PerfCounter();
  15619. this._activeBones = new BABYLON.PerfCounter();
  15620. this._animationTime = 0;
  15621. this.animationTimeScale = 1;
  15622. this._renderId = 0;
  15623. this._executeWhenReadyTimeoutId = -1;
  15624. this._intermediateRendering = false;
  15625. this._viewUpdateFlag = -1;
  15626. this._projectionUpdateFlag = -1;
  15627. this._toBeDisposed = new BABYLON.SmartArray(256);
  15628. this._pendingData = []; //ANY
  15629. this._activeMeshes = new BABYLON.SmartArray(256);
  15630. this._processedMaterials = new BABYLON.SmartArray(256);
  15631. this._renderTargets = new BABYLON.SmartArray(256);
  15632. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15633. this._activeSkeletons = new BABYLON.SmartArray(32);
  15634. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15635. this._activeAnimatables = new Array();
  15636. this._transformMatrix = BABYLON.Matrix.Zero();
  15637. this.requireLightSorting = false;
  15638. this._uniqueIdCounter = 0;
  15639. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15640. this._engine.scenes.push(this);
  15641. this._uid = null;
  15642. this._renderingManager = new BABYLON.RenderingManager(this);
  15643. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15644. if (BABYLON.OutlineRenderer) {
  15645. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15646. }
  15647. this.attachControl();
  15648. if (BABYLON.SoundTrack) {
  15649. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15650. }
  15651. //simplification queue
  15652. if (BABYLON.SimplificationQueue) {
  15653. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15654. }
  15655. //collision coordinator initialization. For now legacy per default.
  15656. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15657. // Uniform Buffer
  15658. this._createUbo();
  15659. // Default Image processing definition.
  15660. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15661. }
  15662. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15663. get: function () {
  15664. return Scene._FOGMODE_NONE;
  15665. },
  15666. enumerable: true,
  15667. configurable: true
  15668. });
  15669. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15670. get: function () {
  15671. return Scene._FOGMODE_EXP;
  15672. },
  15673. enumerable: true,
  15674. configurable: true
  15675. });
  15676. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15677. get: function () {
  15678. return Scene._FOGMODE_EXP2;
  15679. },
  15680. enumerable: true,
  15681. configurable: true
  15682. });
  15683. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15684. get: function () {
  15685. return Scene._FOGMODE_LINEAR;
  15686. },
  15687. enumerable: true,
  15688. configurable: true
  15689. });
  15690. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15691. /**
  15692. * Texture used in all pbr material as the reflection texture.
  15693. * As in the majority of the scene they are the same (exception for multi room and so on),
  15694. * this is easier to reference from here than from all the materials.
  15695. */
  15696. get: function () {
  15697. return this._environmentTexture;
  15698. },
  15699. /**
  15700. * Texture used in all pbr material as the reflection texture.
  15701. * As in the majority of the scene they are the same (exception for multi room and so on),
  15702. * this is easier to set here than in all the materials.
  15703. */
  15704. set: function (value) {
  15705. this._environmentTexture = value;
  15706. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15707. },
  15708. enumerable: true,
  15709. configurable: true
  15710. });
  15711. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15712. /**
  15713. * Default image processing configuration used either in the rendering
  15714. * Forward main pass or through the imageProcessingPostProcess if present.
  15715. * As in the majority of the scene they are the same (exception for multi camera),
  15716. * this is easier to reference from here than from all the materials and post process.
  15717. *
  15718. * No setter as we it is a shared configuration, you can set the values instead.
  15719. */
  15720. get: function () {
  15721. return this._imageProcessingConfiguration;
  15722. },
  15723. enumerable: true,
  15724. configurable: true
  15725. });
  15726. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15727. get: function () {
  15728. return this._forcePointsCloud;
  15729. },
  15730. set: function (value) {
  15731. if (this._forcePointsCloud === value) {
  15732. return;
  15733. }
  15734. this._forcePointsCloud = value;
  15735. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15736. },
  15737. enumerable: true,
  15738. configurable: true
  15739. });
  15740. Object.defineProperty(Scene.prototype, "onDispose", {
  15741. set: function (callback) {
  15742. if (this._onDisposeObserver) {
  15743. this.onDisposeObservable.remove(this._onDisposeObserver);
  15744. }
  15745. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15746. },
  15747. enumerable: true,
  15748. configurable: true
  15749. });
  15750. Object.defineProperty(Scene.prototype, "beforeRender", {
  15751. set: function (callback) {
  15752. if (this._onBeforeRenderObserver) {
  15753. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15754. }
  15755. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(Scene.prototype, "afterRender", {
  15761. set: function (callback) {
  15762. if (this._onAfterRenderObserver) {
  15763. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15764. }
  15765. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15766. },
  15767. enumerable: true,
  15768. configurable: true
  15769. });
  15770. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15771. set: function (callback) {
  15772. if (this._onBeforeCameraRenderObserver) {
  15773. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15774. }
  15775. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15776. },
  15777. enumerable: true,
  15778. configurable: true
  15779. });
  15780. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15781. set: function (callback) {
  15782. if (this._onAfterCameraRenderObserver) {
  15783. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15784. }
  15785. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15786. },
  15787. enumerable: true,
  15788. configurable: true
  15789. });
  15790. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15791. get: function () {
  15792. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15793. },
  15794. enumerable: true,
  15795. configurable: true
  15796. });
  15797. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15798. get: function () {
  15799. return this._useRightHandedSystem;
  15800. },
  15801. set: function (value) {
  15802. if (this._useRightHandedSystem === value) {
  15803. return;
  15804. }
  15805. this._useRightHandedSystem = value;
  15806. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15807. },
  15808. enumerable: true,
  15809. configurable: true
  15810. });
  15811. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15812. get: function () {
  15813. return this._fogEnabled;
  15814. },
  15815. set: function (value) {
  15816. if (this._fogEnabled === value) {
  15817. return;
  15818. }
  15819. this._fogEnabled = value;
  15820. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15821. },
  15822. enumerable: true,
  15823. configurable: true
  15824. });
  15825. Object.defineProperty(Scene.prototype, "fogMode", {
  15826. get: function () {
  15827. return this._fogMode;
  15828. },
  15829. set: function (value) {
  15830. if (this._fogMode === value) {
  15831. return;
  15832. }
  15833. this._fogMode = value;
  15834. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15835. },
  15836. enumerable: true,
  15837. configurable: true
  15838. });
  15839. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15840. get: function () {
  15841. return this._shadowsEnabled;
  15842. },
  15843. set: function (value) {
  15844. if (this._shadowsEnabled === value) {
  15845. return;
  15846. }
  15847. this._shadowsEnabled = value;
  15848. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15854. get: function () {
  15855. return this._lightsEnabled;
  15856. },
  15857. set: function (value) {
  15858. if (this._lightsEnabled === value) {
  15859. return;
  15860. }
  15861. this._lightsEnabled = value;
  15862. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15863. },
  15864. enumerable: true,
  15865. configurable: true
  15866. });
  15867. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15868. get: function () {
  15869. if (!this._defaultMaterial) {
  15870. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15871. }
  15872. return this._defaultMaterial;
  15873. },
  15874. set: function (value) {
  15875. this._defaultMaterial = value;
  15876. },
  15877. enumerable: true,
  15878. configurable: true
  15879. });
  15880. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15881. get: function () {
  15882. return this._texturesEnabled;
  15883. },
  15884. set: function (value) {
  15885. if (this._texturesEnabled === value) {
  15886. return;
  15887. }
  15888. this._texturesEnabled = value;
  15889. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15890. },
  15891. enumerable: true,
  15892. configurable: true
  15893. });
  15894. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15895. get: function () {
  15896. return this._skeletonsEnabled;
  15897. },
  15898. set: function (value) {
  15899. if (this._skeletonsEnabled === value) {
  15900. return;
  15901. }
  15902. this._skeletonsEnabled = value;
  15903. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15909. get: function () {
  15910. if (!this._postProcessRenderPipelineManager) {
  15911. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15912. }
  15913. return this._postProcessRenderPipelineManager;
  15914. },
  15915. enumerable: true,
  15916. configurable: true
  15917. });
  15918. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15919. get: function () {
  15920. return this._frustumPlanes;
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. Object.defineProperty(Scene.prototype, "debugLayer", {
  15926. // Properties
  15927. get: function () {
  15928. if (!this._debugLayer) {
  15929. this._debugLayer = new BABYLON.DebugLayer(this);
  15930. }
  15931. return this._debugLayer;
  15932. },
  15933. enumerable: true,
  15934. configurable: true
  15935. });
  15936. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15937. get: function () {
  15938. return this._workerCollisions;
  15939. },
  15940. set: function (enabled) {
  15941. if (!BABYLON.CollisionCoordinatorLegacy) {
  15942. return;
  15943. }
  15944. enabled = (enabled && !!Worker);
  15945. this._workerCollisions = enabled;
  15946. if (this.collisionCoordinator) {
  15947. this.collisionCoordinator.destroy();
  15948. }
  15949. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15950. this.collisionCoordinator.init(this);
  15951. },
  15952. enumerable: true,
  15953. configurable: true
  15954. });
  15955. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15956. get: function () {
  15957. return this._selectionOctree;
  15958. },
  15959. enumerable: true,
  15960. configurable: true
  15961. });
  15962. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15963. /**
  15964. * The mesh that is currently under the pointer.
  15965. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15966. */
  15967. get: function () {
  15968. return this._pointerOverMesh;
  15969. },
  15970. enumerable: true,
  15971. configurable: true
  15972. });
  15973. Object.defineProperty(Scene.prototype, "pointerX", {
  15974. /**
  15975. * Current on-screen X position of the pointer
  15976. * @return {number} X position of the pointer
  15977. */
  15978. get: function () {
  15979. return this._pointerX;
  15980. },
  15981. enumerable: true,
  15982. configurable: true
  15983. });
  15984. Object.defineProperty(Scene.prototype, "pointerY", {
  15985. /**
  15986. * Current on-screen Y position of the pointer
  15987. * @return {number} Y position of the pointer
  15988. */
  15989. get: function () {
  15990. return this._pointerY;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. Scene.prototype.getCachedMaterial = function () {
  15996. return this._cachedMaterial;
  15997. };
  15998. Scene.prototype.getCachedEffect = function () {
  15999. return this._cachedEffect;
  16000. };
  16001. Scene.prototype.getCachedVisibility = function () {
  16002. return this._cachedVisibility;
  16003. };
  16004. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16005. if (visibility === void 0) { visibility = 0; }
  16006. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16007. };
  16008. Scene.prototype.getBoundingBoxRenderer = function () {
  16009. if (!this._boundingBoxRenderer) {
  16010. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16011. }
  16012. return this._boundingBoxRenderer;
  16013. };
  16014. Scene.prototype.getOutlineRenderer = function () {
  16015. return this._outlineRenderer;
  16016. };
  16017. Scene.prototype.getEngine = function () {
  16018. return this._engine;
  16019. };
  16020. Scene.prototype.getTotalVertices = function () {
  16021. return this._totalVertices.current;
  16022. };
  16023. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16024. get: function () {
  16025. return this._totalVertices;
  16026. },
  16027. enumerable: true,
  16028. configurable: true
  16029. });
  16030. Scene.prototype.getActiveIndices = function () {
  16031. return this._activeIndices.current;
  16032. };
  16033. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16034. get: function () {
  16035. return this._activeIndices;
  16036. },
  16037. enumerable: true,
  16038. configurable: true
  16039. });
  16040. Scene.prototype.getActiveParticles = function () {
  16041. return this._activeParticles.current;
  16042. };
  16043. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16044. get: function () {
  16045. return this._activeParticles;
  16046. },
  16047. enumerable: true,
  16048. configurable: true
  16049. });
  16050. Scene.prototype.getActiveBones = function () {
  16051. return this._activeBones.current;
  16052. };
  16053. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16054. get: function () {
  16055. return this._activeBones;
  16056. },
  16057. enumerable: true,
  16058. configurable: true
  16059. });
  16060. // Stats
  16061. Scene.prototype.getLastFrameDuration = function () {
  16062. return this._lastFrameDuration.current;
  16063. };
  16064. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16065. get: function () {
  16066. return this._lastFrameDuration;
  16067. },
  16068. enumerable: true,
  16069. configurable: true
  16070. });
  16071. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16072. return this._evaluateActiveMeshesDuration.current;
  16073. };
  16074. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16075. get: function () {
  16076. return this._evaluateActiveMeshesDuration;
  16077. },
  16078. enumerable: true,
  16079. configurable: true
  16080. });
  16081. Scene.prototype.getActiveMeshes = function () {
  16082. return this._activeMeshes;
  16083. };
  16084. Scene.prototype.getRenderTargetsDuration = function () {
  16085. return this._renderTargetsDuration.current;
  16086. };
  16087. Scene.prototype.getRenderDuration = function () {
  16088. return this._renderDuration.current;
  16089. };
  16090. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16091. get: function () {
  16092. return this._renderDuration;
  16093. },
  16094. enumerable: true,
  16095. configurable: true
  16096. });
  16097. Scene.prototype.getParticlesDuration = function () {
  16098. return this._particlesDuration.current;
  16099. };
  16100. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16101. get: function () {
  16102. return this._particlesDuration;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Scene.prototype.getSpritesDuration = function () {
  16108. return this._spritesDuration.current;
  16109. };
  16110. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16111. get: function () {
  16112. return this._spritesDuration;
  16113. },
  16114. enumerable: true,
  16115. configurable: true
  16116. });
  16117. Scene.prototype.getAnimationRatio = function () {
  16118. return this._animationRatio;
  16119. };
  16120. Scene.prototype.getRenderId = function () {
  16121. return this._renderId;
  16122. };
  16123. Scene.prototype.incrementRenderId = function () {
  16124. this._renderId++;
  16125. };
  16126. Scene.prototype._updatePointerPosition = function (evt) {
  16127. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16128. this._pointerX = evt.clientX - canvasRect.left;
  16129. this._pointerY = evt.clientY - canvasRect.top;
  16130. this._unTranslatedPointerX = this._pointerX;
  16131. this._unTranslatedPointerY = this._pointerY;
  16132. if (this.cameraToUseForPointers) {
  16133. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16134. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16135. }
  16136. };
  16137. Scene.prototype._createUbo = function () {
  16138. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16139. this._sceneUbo.addUniform("viewProjection", 16);
  16140. this._sceneUbo.addUniform("view", 16);
  16141. };
  16142. // Pointers handling
  16143. /**
  16144. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16145. * @param attachUp defines if you want to attach events to pointerup
  16146. * @param attachDown defines if you want to attach events to pointerdown
  16147. * @param attachMove defines if you want to attach events to pointermove
  16148. */
  16149. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16150. var _this = this;
  16151. if (attachUp === void 0) { attachUp = true; }
  16152. if (attachDown === void 0) { attachDown = true; }
  16153. if (attachMove === void 0) { attachMove = true; }
  16154. this._initActionManager = function (act, clickInfo) {
  16155. if (!_this._meshPickProceed) {
  16156. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16157. _this._currentPickResult = pickResult;
  16158. if (pickResult) {
  16159. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16160. }
  16161. _this._meshPickProceed = true;
  16162. }
  16163. return act;
  16164. };
  16165. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16166. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16167. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16168. btn !== _this._previousButtonPressed) {
  16169. _this._doubleClickOccured = false;
  16170. clickInfo.singleClick = true;
  16171. clickInfo.ignore = false;
  16172. cb(clickInfo, _this._currentPickResult);
  16173. }
  16174. };
  16175. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16176. var clickInfo = new ClickInfo();
  16177. _this._currentPickResult = null;
  16178. var act;
  16179. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16180. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16181. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16182. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16183. act = _this._initActionManager(act, clickInfo);
  16184. if (act)
  16185. checkPicking = act.hasPickTriggers;
  16186. }
  16187. if (checkPicking) {
  16188. var btn = evt.button;
  16189. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16190. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16191. if (!clickInfo.hasSwiped) {
  16192. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16193. if (!checkSingleClickImmediately) {
  16194. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16195. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16196. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16197. act = _this._initActionManager(act, clickInfo);
  16198. if (act)
  16199. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16200. }
  16201. }
  16202. if (checkSingleClickImmediately) {
  16203. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16204. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16205. btn !== _this._previousButtonPressed) {
  16206. clickInfo.singleClick = true;
  16207. cb(clickInfo, _this._currentPickResult);
  16208. }
  16209. }
  16210. else {
  16211. // wait that no double click has been raised during the double click delay
  16212. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16213. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16214. }
  16215. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16216. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16217. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16218. act = _this._initActionManager(act, clickInfo);
  16219. if (act)
  16220. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16221. }
  16222. if (checkDoubleClick) {
  16223. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16224. if (btn === _this._previousButtonPressed &&
  16225. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16226. !_this._doubleClickOccured) {
  16227. // pointer has not moved for 2 clicks, it's a double click
  16228. if (!clickInfo.hasSwiped &&
  16229. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16230. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16231. _this._previousStartingPointerTime = 0;
  16232. _this._doubleClickOccured = true;
  16233. clickInfo.doubleClick = true;
  16234. clickInfo.ignore = false;
  16235. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16236. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16237. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16238. cb(clickInfo, _this._currentPickResult);
  16239. }
  16240. else {
  16241. _this._doubleClickOccured = false;
  16242. _this._previousStartingPointerTime = _this._startingPointerTime;
  16243. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16244. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16245. _this._previousButtonPressed = btn;
  16246. _this._previousHasSwiped = clickInfo.hasSwiped;
  16247. if (Scene.ExclusiveDoubleClickMode) {
  16248. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16249. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16250. }
  16251. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16252. cb(clickInfo, _this._previousPickResult);
  16253. }
  16254. else {
  16255. cb(clickInfo, _this._currentPickResult);
  16256. }
  16257. }
  16258. }
  16259. else {
  16260. _this._doubleClickOccured = false;
  16261. _this._previousStartingPointerTime = _this._startingPointerTime;
  16262. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16263. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16264. _this._previousButtonPressed = btn;
  16265. _this._previousHasSwiped = clickInfo.hasSwiped;
  16266. }
  16267. }
  16268. }
  16269. }
  16270. clickInfo.ignore = true;
  16271. cb(clickInfo, _this._currentPickResult);
  16272. };
  16273. var spritePredicate = function (sprite) {
  16274. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16275. };
  16276. this._onPointerMove = function (evt) {
  16277. _this._updatePointerPosition(evt);
  16278. // PreObservable support
  16279. if (_this.onPrePointerObservable.hasObservers()) {
  16280. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16281. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16282. _this.onPrePointerObservable.notifyObservers(pi, type);
  16283. if (pi.skipOnPointerObservable) {
  16284. return;
  16285. }
  16286. }
  16287. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16288. return;
  16289. }
  16290. var canvas = _this._engine.getRenderingCanvas();
  16291. if (!_this.pointerMovePredicate) {
  16292. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16293. }
  16294. // Meshes
  16295. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16296. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16297. _this.setPointerOverSprite(null);
  16298. _this.setPointerOverMesh(pickResult.pickedMesh);
  16299. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16300. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16301. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16302. }
  16303. else {
  16304. canvas.style.cursor = _this.hoverCursor;
  16305. }
  16306. }
  16307. else {
  16308. canvas.style.cursor = "";
  16309. }
  16310. }
  16311. else {
  16312. _this.setPointerOverMesh(null);
  16313. // Sprites
  16314. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16315. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16316. _this.setPointerOverSprite(pickResult.pickedSprite);
  16317. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16318. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16319. }
  16320. else {
  16321. canvas.style.cursor = _this.hoverCursor;
  16322. }
  16323. }
  16324. else {
  16325. _this.setPointerOverSprite(null);
  16326. // Restore pointer
  16327. canvas.style.cursor = "";
  16328. }
  16329. }
  16330. if (_this.onPointerMove) {
  16331. _this.onPointerMove(evt, pickResult);
  16332. }
  16333. if (_this.onPointerObservable.hasObservers()) {
  16334. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16335. var pi = new PointerInfo(type, evt, pickResult);
  16336. _this.onPointerObservable.notifyObservers(pi, type);
  16337. }
  16338. };
  16339. this._onPointerDown = function (evt) {
  16340. _this._isButtonPressed = true;
  16341. _this._pickedDownMesh = null;
  16342. _this._meshPickProceed = false;
  16343. _this._updatePointerPosition(evt);
  16344. // PreObservable support
  16345. if (_this.onPrePointerObservable.hasObservers()) {
  16346. var type = PointerEventTypes.POINTERDOWN;
  16347. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16348. _this.onPrePointerObservable.notifyObservers(pi, type);
  16349. if (pi.skipOnPointerObservable) {
  16350. return;
  16351. }
  16352. }
  16353. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16354. return;
  16355. }
  16356. _this._startingPointerPosition.x = _this._pointerX;
  16357. _this._startingPointerPosition.y = _this._pointerY;
  16358. _this._startingPointerTime = new Date().getTime();
  16359. if (!_this.pointerDownPredicate) {
  16360. _this.pointerDownPredicate = function (mesh) {
  16361. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16362. };
  16363. }
  16364. // Meshes
  16365. _this._pickedDownMesh = null;
  16366. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16367. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16368. _this._pickedDownMesh = pickResult.pickedMesh;
  16369. var actionManager = pickResult.pickedMesh.actionManager;
  16370. if (actionManager) {
  16371. if (actionManager.hasPickTriggers) {
  16372. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16373. switch (evt.button) {
  16374. case 0:
  16375. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16376. break;
  16377. case 1:
  16378. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16379. break;
  16380. case 2:
  16381. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16382. break;
  16383. }
  16384. }
  16385. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16386. window.setTimeout((function () {
  16387. var _this = this;
  16388. 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);
  16389. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16390. if (this._isButtonPressed &&
  16391. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16392. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16393. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16394. this._startingPointerTime = 0;
  16395. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16396. }
  16397. }
  16398. }).bind(_this), Scene.LongPressDelay);
  16399. }
  16400. }
  16401. }
  16402. if (_this.onPointerDown) {
  16403. _this.onPointerDown(evt, pickResult);
  16404. }
  16405. if (_this.onPointerObservable.hasObservers()) {
  16406. var type = PointerEventTypes.POINTERDOWN;
  16407. var pi = new PointerInfo(type, evt, pickResult);
  16408. _this.onPointerObservable.notifyObservers(pi, type);
  16409. }
  16410. // Sprites
  16411. _this._pickedDownSprite = null;
  16412. if (_this.spriteManagers.length > 0) {
  16413. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16414. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16415. if (pickResult.pickedSprite.actionManager) {
  16416. _this._pickedDownSprite = pickResult.pickedSprite;
  16417. switch (evt.button) {
  16418. case 0:
  16419. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16420. break;
  16421. case 1:
  16422. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16423. break;
  16424. case 2:
  16425. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16426. break;
  16427. }
  16428. if (pickResult.pickedSprite.actionManager) {
  16429. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16430. }
  16431. }
  16432. }
  16433. }
  16434. };
  16435. this._onPointerUp = function (evt) {
  16436. _this._isButtonPressed = false;
  16437. _this._pickedUpMesh = null;
  16438. _this._meshPickProceed = false;
  16439. _this._updatePointerPosition(evt);
  16440. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16441. // PreObservable support
  16442. if (this.onPrePointerObservable.hasObservers()) {
  16443. if (!clickInfo.ignore) {
  16444. if (!clickInfo.hasSwiped) {
  16445. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16446. var type = PointerEventTypes.POINTERTAP;
  16447. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16448. this.onPrePointerObservable.notifyObservers(pi, type);
  16449. if (pi.skipOnPointerObservable) {
  16450. return;
  16451. }
  16452. }
  16453. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16454. var type = PointerEventTypes.POINTERDOUBLETAP;
  16455. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16456. this.onPrePointerObservable.notifyObservers(pi, type);
  16457. if (pi.skipOnPointerObservable) {
  16458. return;
  16459. }
  16460. }
  16461. }
  16462. }
  16463. else {
  16464. var type = PointerEventTypes.POINTERUP;
  16465. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16466. this.onPrePointerObservable.notifyObservers(pi, type);
  16467. if (pi.skipOnPointerObservable) {
  16468. return;
  16469. }
  16470. }
  16471. }
  16472. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16473. return;
  16474. }
  16475. if (!this.pointerUpPredicate) {
  16476. this.pointerUpPredicate = function (mesh) {
  16477. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16478. };
  16479. }
  16480. // Meshes
  16481. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16482. this._initActionManager(null, clickInfo);
  16483. }
  16484. if (!pickResult) {
  16485. pickResult = this._currentPickResult;
  16486. }
  16487. if (pickResult && pickResult && pickResult.pickedMesh) {
  16488. this._pickedUpMesh = pickResult.pickedMesh;
  16489. if (this._pickedDownMesh === this._pickedUpMesh) {
  16490. if (this.onPointerPick) {
  16491. this.onPointerPick(evt, pickResult);
  16492. }
  16493. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16494. var type = PointerEventTypes.POINTERPICK;
  16495. var pi = new PointerInfo(type, evt, pickResult);
  16496. this.onPointerObservable.notifyObservers(pi, type);
  16497. }
  16498. }
  16499. if (pickResult.pickedMesh.actionManager) {
  16500. if (clickInfo.ignore) {
  16501. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16502. }
  16503. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16504. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16505. }
  16506. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16507. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16508. }
  16509. }
  16510. }
  16511. if (this._pickedDownMesh &&
  16512. this._pickedDownMesh.actionManager &&
  16513. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16514. this._pickedDownMesh !== this._pickedUpMesh) {
  16515. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16516. }
  16517. if (this.onPointerUp) {
  16518. this.onPointerUp(evt, pickResult);
  16519. }
  16520. if (this.onPointerObservable.hasObservers()) {
  16521. if (!clickInfo.ignore) {
  16522. if (!clickInfo.hasSwiped) {
  16523. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16524. var type = PointerEventTypes.POINTERTAP;
  16525. var pi = new PointerInfo(type, evt, pickResult);
  16526. this.onPointerObservable.notifyObservers(pi, type);
  16527. }
  16528. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16529. var type = PointerEventTypes.POINTERDOUBLETAP;
  16530. var pi = new PointerInfo(type, evt, pickResult);
  16531. this.onPointerObservable.notifyObservers(pi, type);
  16532. }
  16533. }
  16534. }
  16535. else {
  16536. var type = PointerEventTypes.POINTERUP;
  16537. var pi = new PointerInfo(type, evt, pickResult);
  16538. this.onPointerObservable.notifyObservers(pi, type);
  16539. }
  16540. }
  16541. // Sprites
  16542. if (this.spriteManagers.length > 0) {
  16543. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16544. if (pickResult.hit && pickResult.pickedSprite) {
  16545. if (pickResult.pickedSprite.actionManager) {
  16546. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16547. if (pickResult.pickedSprite.actionManager) {
  16548. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16549. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16550. }
  16551. }
  16552. }
  16553. }
  16554. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16555. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16556. }
  16557. }
  16558. this._previousPickResult = this._currentPickResult;
  16559. }).bind(_this));
  16560. };
  16561. this._onKeyDown = function (evt) {
  16562. if (_this.actionManager) {
  16563. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16564. }
  16565. };
  16566. this._onKeyUp = function (evt) {
  16567. if (_this.actionManager) {
  16568. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16569. }
  16570. };
  16571. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16572. var canvas = this._engine.getRenderingCanvas();
  16573. if (attachMove) {
  16574. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16575. // Wheel
  16576. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16577. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16578. }
  16579. if (attachDown) {
  16580. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16581. }
  16582. if (attachUp) {
  16583. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16584. }
  16585. canvas.tabIndex = 1;
  16586. canvas.addEventListener("keydown", this._onKeyDown, false);
  16587. canvas.addEventListener("keyup", this._onKeyUp, false);
  16588. };
  16589. Scene.prototype.detachControl = function () {
  16590. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16591. var canvas = this._engine.getRenderingCanvas();
  16592. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16593. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16594. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16595. // Wheel
  16596. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16597. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16598. canvas.removeEventListener("keydown", this._onKeyDown);
  16599. canvas.removeEventListener("keyup", this._onKeyUp);
  16600. };
  16601. // Ready
  16602. Scene.prototype.isReady = function () {
  16603. if (this._pendingData.length > 0) {
  16604. return false;
  16605. }
  16606. var index;
  16607. // Geometries
  16608. for (index = 0; index < this._geometries.length; index++) {
  16609. var geometry = this._geometries[index];
  16610. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16611. return false;
  16612. }
  16613. }
  16614. // Meshes
  16615. for (index = 0; index < this.meshes.length; index++) {
  16616. var mesh = this.meshes[index];
  16617. if (!mesh.isEnabled()) {
  16618. continue;
  16619. }
  16620. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16621. continue;
  16622. }
  16623. if (!mesh.isReady()) {
  16624. return false;
  16625. }
  16626. var mat = mesh.material;
  16627. if (mat) {
  16628. if (!mat.isReady(mesh)) {
  16629. return false;
  16630. }
  16631. }
  16632. }
  16633. return true;
  16634. };
  16635. Scene.prototype.resetCachedMaterial = function () {
  16636. this._cachedMaterial = null;
  16637. this._cachedEffect = null;
  16638. this._cachedVisibility = null;
  16639. };
  16640. Scene.prototype.registerBeforeRender = function (func) {
  16641. this.onBeforeRenderObservable.add(func);
  16642. };
  16643. Scene.prototype.unregisterBeforeRender = function (func) {
  16644. this.onBeforeRenderObservable.removeCallback(func);
  16645. };
  16646. Scene.prototype.registerAfterRender = function (func) {
  16647. this.onAfterRenderObservable.add(func);
  16648. };
  16649. Scene.prototype.unregisterAfterRender = function (func) {
  16650. this.onAfterRenderObservable.removeCallback(func);
  16651. };
  16652. Scene.prototype._addPendingData = function (data) {
  16653. this._pendingData.push(data);
  16654. };
  16655. Scene.prototype._removePendingData = function (data) {
  16656. var index = this._pendingData.indexOf(data);
  16657. if (index !== -1) {
  16658. this._pendingData.splice(index, 1);
  16659. }
  16660. };
  16661. Scene.prototype.getWaitingItemsCount = function () {
  16662. return this._pendingData.length;
  16663. };
  16664. /**
  16665. * Registers a function to be executed when the scene is ready.
  16666. * @param {Function} func - the function to be executed.
  16667. */
  16668. Scene.prototype.executeWhenReady = function (func) {
  16669. var _this = this;
  16670. this.onReadyObservable.add(func);
  16671. if (this._executeWhenReadyTimeoutId !== -1) {
  16672. return;
  16673. }
  16674. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16675. _this._checkIsReady();
  16676. }, 150);
  16677. };
  16678. Scene.prototype._checkIsReady = function () {
  16679. var _this = this;
  16680. if (this.isReady()) {
  16681. this.onReadyObservable.notifyObservers(this);
  16682. this.onReadyObservable.clear();
  16683. this._executeWhenReadyTimeoutId = -1;
  16684. return;
  16685. }
  16686. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16687. _this._checkIsReady();
  16688. }, 150);
  16689. };
  16690. // Animations
  16691. /**
  16692. * Will start the animation sequence of a given target
  16693. * @param target - the target
  16694. * @param {number} from - from which frame should animation start
  16695. * @param {number} to - till which frame should animation run.
  16696. * @param {boolean} [loop] - should the animation loop
  16697. * @param {number} [speedRatio] - the speed in which to run the animation
  16698. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16699. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16700. * @return {BABYLON.Animatable} the animatable object created for this animation
  16701. * @see BABYLON.Animatable
  16702. * @see http://doc.babylonjs.com/page.php?p=22081
  16703. */
  16704. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16705. if (speedRatio === void 0) { speedRatio = 1.0; }
  16706. if (from > to && speedRatio > 0) {
  16707. speedRatio *= -1;
  16708. }
  16709. this.stopAnimation(target);
  16710. if (!animatable) {
  16711. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16712. }
  16713. // Local animations
  16714. if (target.animations) {
  16715. animatable.appendAnimations(target, target.animations);
  16716. }
  16717. // Children animations
  16718. if (target.getAnimatables) {
  16719. var animatables = target.getAnimatables();
  16720. for (var index = 0; index < animatables.length; index++) {
  16721. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16722. }
  16723. }
  16724. animatable.reset();
  16725. return animatable;
  16726. };
  16727. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16728. if (speedRatio === undefined) {
  16729. speedRatio = 1.0;
  16730. }
  16731. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16732. return animatable;
  16733. };
  16734. Scene.prototype.getAnimatableByTarget = function (target) {
  16735. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16736. if (this._activeAnimatables[index].target === target) {
  16737. return this._activeAnimatables[index];
  16738. }
  16739. }
  16740. return null;
  16741. };
  16742. Object.defineProperty(Scene.prototype, "Animatables", {
  16743. get: function () {
  16744. return this._activeAnimatables;
  16745. },
  16746. enumerable: true,
  16747. configurable: true
  16748. });
  16749. /**
  16750. * Will stop the animation of the given target
  16751. * @param target - the target
  16752. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16753. * @see beginAnimation
  16754. */
  16755. Scene.prototype.stopAnimation = function (target, animationName) {
  16756. var animatable = this.getAnimatableByTarget(target);
  16757. if (animatable) {
  16758. animatable.stop(animationName);
  16759. }
  16760. };
  16761. Scene.prototype._animate = function () {
  16762. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16763. return;
  16764. }
  16765. // Getting time
  16766. var now = BABYLON.Tools.Now;
  16767. if (!this._animationTimeLast) {
  16768. if (this._pendingData.length > 0) {
  16769. return;
  16770. }
  16771. this._animationTimeLast = now;
  16772. }
  16773. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16774. this._animationTime += deltaTime;
  16775. this._animationTimeLast = now;
  16776. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16777. this._activeAnimatables[index]._animate(this._animationTime);
  16778. }
  16779. };
  16780. // Matrix
  16781. Scene.prototype.getViewMatrix = function () {
  16782. return this._viewMatrix;
  16783. };
  16784. Scene.prototype.getProjectionMatrix = function () {
  16785. return this._projectionMatrix;
  16786. };
  16787. Scene.prototype.getTransformMatrix = function () {
  16788. return this._transformMatrix;
  16789. };
  16790. Scene.prototype.setTransformMatrix = function (view, projection) {
  16791. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16792. return;
  16793. }
  16794. this._viewUpdateFlag = view.updateFlag;
  16795. this._projectionUpdateFlag = projection.updateFlag;
  16796. this._viewMatrix = view;
  16797. this._projectionMatrix = projection;
  16798. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16799. // Update frustum
  16800. if (!this._frustumPlanes) {
  16801. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16802. }
  16803. else {
  16804. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16805. }
  16806. if (this._sceneUbo.useUbo) {
  16807. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16808. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16809. this._sceneUbo.update();
  16810. }
  16811. };
  16812. Scene.prototype.getSceneUniformBuffer = function () {
  16813. return this._sceneUbo;
  16814. };
  16815. // Methods
  16816. Scene.prototype.getUniqueId = function () {
  16817. var result = this._uniqueIdCounter;
  16818. this._uniqueIdCounter++;
  16819. return result;
  16820. };
  16821. Scene.prototype.addMesh = function (newMesh) {
  16822. newMesh.uniqueId = this.getUniqueId();
  16823. var position = this.meshes.push(newMesh);
  16824. //notify the collision coordinator
  16825. if (this.collisionCoordinator) {
  16826. this.collisionCoordinator.onMeshAdded(newMesh);
  16827. }
  16828. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16829. };
  16830. Scene.prototype.removeMesh = function (toRemove) {
  16831. var index = this.meshes.indexOf(toRemove);
  16832. if (index !== -1) {
  16833. // Remove from the scene if mesh found
  16834. this.meshes.splice(index, 1);
  16835. }
  16836. //notify the collision coordinator
  16837. if (this.collisionCoordinator) {
  16838. this.collisionCoordinator.onMeshRemoved(toRemove);
  16839. }
  16840. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16841. return index;
  16842. };
  16843. Scene.prototype.removeSkeleton = function (toRemove) {
  16844. var index = this.skeletons.indexOf(toRemove);
  16845. if (index !== -1) {
  16846. // Remove from the scene if found
  16847. this.skeletons.splice(index, 1);
  16848. }
  16849. return index;
  16850. };
  16851. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16852. var index = this.morphTargetManagers.indexOf(toRemove);
  16853. if (index !== -1) {
  16854. // Remove from the scene if found
  16855. this.morphTargetManagers.splice(index, 1);
  16856. }
  16857. return index;
  16858. };
  16859. Scene.prototype.removeLight = function (toRemove) {
  16860. var index = this.lights.indexOf(toRemove);
  16861. if (index !== -1) {
  16862. // Remove from the scene if mesh found
  16863. this.lights.splice(index, 1);
  16864. this.sortLightsByPriority();
  16865. }
  16866. this.onLightRemovedObservable.notifyObservers(toRemove);
  16867. return index;
  16868. };
  16869. Scene.prototype.removeCamera = function (toRemove) {
  16870. var index = this.cameras.indexOf(toRemove);
  16871. if (index !== -1) {
  16872. // Remove from the scene if mesh found
  16873. this.cameras.splice(index, 1);
  16874. }
  16875. // Remove from activeCameras
  16876. var index2 = this.activeCameras.indexOf(toRemove);
  16877. if (index2 !== -1) {
  16878. // Remove from the scene if mesh found
  16879. this.activeCameras.splice(index2, 1);
  16880. }
  16881. // Reset the activeCamera
  16882. if (this.activeCamera === toRemove) {
  16883. if (this.cameras.length > 0) {
  16884. this.activeCamera = this.cameras[0];
  16885. }
  16886. else {
  16887. this.activeCamera = null;
  16888. }
  16889. }
  16890. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16891. return index;
  16892. };
  16893. Scene.prototype.addLight = function (newLight) {
  16894. newLight.uniqueId = this.getUniqueId();
  16895. this.lights.push(newLight);
  16896. this.sortLightsByPriority();
  16897. this.onNewLightAddedObservable.notifyObservers(newLight);
  16898. };
  16899. Scene.prototype.sortLightsByPriority = function () {
  16900. if (this.requireLightSorting) {
  16901. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16902. }
  16903. };
  16904. Scene.prototype.addCamera = function (newCamera) {
  16905. newCamera.uniqueId = this.getUniqueId();
  16906. var position = this.cameras.push(newCamera);
  16907. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16908. };
  16909. /**
  16910. * Switch active camera
  16911. * @param {Camera} newCamera - new active camera
  16912. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16913. */
  16914. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16915. if (attachControl === void 0) { attachControl = true; }
  16916. var canvas = this._engine.getRenderingCanvas();
  16917. this.activeCamera.detachControl(canvas);
  16918. this.activeCamera = newCamera;
  16919. if (attachControl) {
  16920. newCamera.attachControl(canvas);
  16921. }
  16922. };
  16923. /**
  16924. * sets the active camera of the scene using its ID
  16925. * @param {string} id - the camera's ID
  16926. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16927. * @see activeCamera
  16928. */
  16929. Scene.prototype.setActiveCameraByID = function (id) {
  16930. var camera = this.getCameraByID(id);
  16931. if (camera) {
  16932. this.activeCamera = camera;
  16933. return camera;
  16934. }
  16935. return null;
  16936. };
  16937. /**
  16938. * sets the active camera of the scene using its name
  16939. * @param {string} name - the camera's name
  16940. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16941. * @see activeCamera
  16942. */
  16943. Scene.prototype.setActiveCameraByName = function (name) {
  16944. var camera = this.getCameraByName(name);
  16945. if (camera) {
  16946. this.activeCamera = camera;
  16947. return camera;
  16948. }
  16949. return null;
  16950. };
  16951. /**
  16952. * get a material using its id
  16953. * @param {string} the material's ID
  16954. * @return {BABYLON.Material|null} the material or null if none found.
  16955. */
  16956. Scene.prototype.getMaterialByID = function (id) {
  16957. for (var index = 0; index < this.materials.length; index++) {
  16958. if (this.materials[index].id === id) {
  16959. return this.materials[index];
  16960. }
  16961. }
  16962. return null;
  16963. };
  16964. /**
  16965. * get a material using its name
  16966. * @param {string} the material's name
  16967. * @return {BABYLON.Material|null} the material or null if none found.
  16968. */
  16969. Scene.prototype.getMaterialByName = function (name) {
  16970. for (var index = 0; index < this.materials.length; index++) {
  16971. if (this.materials[index].name === name) {
  16972. return this.materials[index];
  16973. }
  16974. }
  16975. return null;
  16976. };
  16977. Scene.prototype.getLensFlareSystemByName = function (name) {
  16978. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16979. if (this.lensFlareSystems[index].name === name) {
  16980. return this.lensFlareSystems[index];
  16981. }
  16982. }
  16983. return null;
  16984. };
  16985. Scene.prototype.getLensFlareSystemByID = function (id) {
  16986. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16987. if (this.lensFlareSystems[index].id === id) {
  16988. return this.lensFlareSystems[index];
  16989. }
  16990. }
  16991. return null;
  16992. };
  16993. Scene.prototype.getCameraByID = function (id) {
  16994. for (var index = 0; index < this.cameras.length; index++) {
  16995. if (this.cameras[index].id === id) {
  16996. return this.cameras[index];
  16997. }
  16998. }
  16999. return null;
  17000. };
  17001. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17002. for (var index = 0; index < this.cameras.length; index++) {
  17003. if (this.cameras[index].uniqueId === uniqueId) {
  17004. return this.cameras[index];
  17005. }
  17006. }
  17007. return null;
  17008. };
  17009. /**
  17010. * get a camera using its name
  17011. * @param {string} the camera's name
  17012. * @return {BABYLON.Camera|null} the camera or null if none found.
  17013. */
  17014. Scene.prototype.getCameraByName = function (name) {
  17015. for (var index = 0; index < this.cameras.length; index++) {
  17016. if (this.cameras[index].name === name) {
  17017. return this.cameras[index];
  17018. }
  17019. }
  17020. return null;
  17021. };
  17022. /**
  17023. * get a bone using its id
  17024. * @param {string} the bone's id
  17025. * @return {BABYLON.Bone|null} the bone or null if not found
  17026. */
  17027. Scene.prototype.getBoneByID = function (id) {
  17028. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17029. var skeleton = this.skeletons[skeletonIndex];
  17030. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17031. if (skeleton.bones[boneIndex].id === id) {
  17032. return skeleton.bones[boneIndex];
  17033. }
  17034. }
  17035. }
  17036. return null;
  17037. };
  17038. /**
  17039. * get a bone using its id
  17040. * @param {string} the bone's name
  17041. * @return {BABYLON.Bone|null} the bone or null if not found
  17042. */
  17043. Scene.prototype.getBoneByName = function (name) {
  17044. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17045. var skeleton = this.skeletons[skeletonIndex];
  17046. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17047. if (skeleton.bones[boneIndex].name === name) {
  17048. return skeleton.bones[boneIndex];
  17049. }
  17050. }
  17051. }
  17052. return null;
  17053. };
  17054. /**
  17055. * get a light node using its name
  17056. * @param {string} the light's name
  17057. * @return {BABYLON.Light|null} the light or null if none found.
  17058. */
  17059. Scene.prototype.getLightByName = function (name) {
  17060. for (var index = 0; index < this.lights.length; index++) {
  17061. if (this.lights[index].name === name) {
  17062. return this.lights[index];
  17063. }
  17064. }
  17065. return null;
  17066. };
  17067. /**
  17068. * get a light node using its ID
  17069. * @param {string} the light's id
  17070. * @return {BABYLON.Light|null} the light or null if none found.
  17071. */
  17072. Scene.prototype.getLightByID = function (id) {
  17073. for (var index = 0; index < this.lights.length; index++) {
  17074. if (this.lights[index].id === id) {
  17075. return this.lights[index];
  17076. }
  17077. }
  17078. return null;
  17079. };
  17080. /**
  17081. * get a light node using its scene-generated unique ID
  17082. * @param {number} the light's unique id
  17083. * @return {BABYLON.Light|null} the light or null if none found.
  17084. */
  17085. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17086. for (var index = 0; index < this.lights.length; index++) {
  17087. if (this.lights[index].uniqueId === uniqueId) {
  17088. return this.lights[index];
  17089. }
  17090. }
  17091. return null;
  17092. };
  17093. /**
  17094. * get a particle system by id
  17095. * @param id {number} the particle system id
  17096. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17097. */
  17098. Scene.prototype.getParticleSystemByID = function (id) {
  17099. for (var index = 0; index < this.particleSystems.length; index++) {
  17100. if (this.particleSystems[index].id === id) {
  17101. return this.particleSystems[index];
  17102. }
  17103. }
  17104. return null;
  17105. };
  17106. /**
  17107. * get a geometry using its ID
  17108. * @param {string} the geometry's id
  17109. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17110. */
  17111. Scene.prototype.getGeometryByID = function (id) {
  17112. for (var index = 0; index < this._geometries.length; index++) {
  17113. if (this._geometries[index].id === id) {
  17114. return this._geometries[index];
  17115. }
  17116. }
  17117. return null;
  17118. };
  17119. /**
  17120. * add a new geometry to this scene.
  17121. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17122. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17123. * @return {boolean} was the geometry added or not
  17124. */
  17125. Scene.prototype.pushGeometry = function (geometry, force) {
  17126. if (!force && this.getGeometryByID(geometry.id)) {
  17127. return false;
  17128. }
  17129. this._geometries.push(geometry);
  17130. //notify the collision coordinator
  17131. if (this.collisionCoordinator) {
  17132. this.collisionCoordinator.onGeometryAdded(geometry);
  17133. }
  17134. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17135. return true;
  17136. };
  17137. /**
  17138. * Removes an existing geometry
  17139. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17140. * @return {boolean} was the geometry removed or not
  17141. */
  17142. Scene.prototype.removeGeometry = function (geometry) {
  17143. var index = this._geometries.indexOf(geometry);
  17144. if (index > -1) {
  17145. this._geometries.splice(index, 1);
  17146. //notify the collision coordinator
  17147. if (this.collisionCoordinator) {
  17148. this.collisionCoordinator.onGeometryDeleted(geometry);
  17149. }
  17150. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17151. return true;
  17152. }
  17153. return false;
  17154. };
  17155. Scene.prototype.getGeometries = function () {
  17156. return this._geometries;
  17157. };
  17158. /**
  17159. * Get the first added mesh found of a given ID
  17160. * @param {string} id - the id to search for
  17161. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17162. */
  17163. Scene.prototype.getMeshByID = function (id) {
  17164. for (var index = 0; index < this.meshes.length; index++) {
  17165. if (this.meshes[index].id === id) {
  17166. return this.meshes[index];
  17167. }
  17168. }
  17169. return null;
  17170. };
  17171. Scene.prototype.getMeshesByID = function (id) {
  17172. return this.meshes.filter(function (m) {
  17173. return m.id === id;
  17174. });
  17175. };
  17176. /**
  17177. * Get a mesh with its auto-generated unique id
  17178. * @param {number} uniqueId - the unique id to search for
  17179. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17180. */
  17181. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17182. for (var index = 0; index < this.meshes.length; index++) {
  17183. if (this.meshes[index].uniqueId === uniqueId) {
  17184. return this.meshes[index];
  17185. }
  17186. }
  17187. return null;
  17188. };
  17189. /**
  17190. * Get a the last added mesh found of a given ID
  17191. * @param {string} id - the id to search for
  17192. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17193. */
  17194. Scene.prototype.getLastMeshByID = function (id) {
  17195. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17196. if (this.meshes[index].id === id) {
  17197. return this.meshes[index];
  17198. }
  17199. }
  17200. return null;
  17201. };
  17202. /**
  17203. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17204. * @param {string} id - the id to search for
  17205. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17206. */
  17207. Scene.prototype.getLastEntryByID = function (id) {
  17208. var index;
  17209. for (index = this.meshes.length - 1; index >= 0; index--) {
  17210. if (this.meshes[index].id === id) {
  17211. return this.meshes[index];
  17212. }
  17213. }
  17214. for (index = this.cameras.length - 1; index >= 0; index--) {
  17215. if (this.cameras[index].id === id) {
  17216. return this.cameras[index];
  17217. }
  17218. }
  17219. for (index = this.lights.length - 1; index >= 0; index--) {
  17220. if (this.lights[index].id === id) {
  17221. return this.lights[index];
  17222. }
  17223. }
  17224. return null;
  17225. };
  17226. Scene.prototype.getNodeByID = function (id) {
  17227. var mesh = this.getMeshByID(id);
  17228. if (mesh) {
  17229. return mesh;
  17230. }
  17231. var light = this.getLightByID(id);
  17232. if (light) {
  17233. return light;
  17234. }
  17235. var camera = this.getCameraByID(id);
  17236. if (camera) {
  17237. return camera;
  17238. }
  17239. var bone = this.getBoneByID(id);
  17240. return bone;
  17241. };
  17242. Scene.prototype.getNodeByName = function (name) {
  17243. var mesh = this.getMeshByName(name);
  17244. if (mesh) {
  17245. return mesh;
  17246. }
  17247. var light = this.getLightByName(name);
  17248. if (light) {
  17249. return light;
  17250. }
  17251. var camera = this.getCameraByName(name);
  17252. if (camera) {
  17253. return camera;
  17254. }
  17255. var bone = this.getBoneByName(name);
  17256. return bone;
  17257. };
  17258. Scene.prototype.getMeshByName = function (name) {
  17259. for (var index = 0; index < this.meshes.length; index++) {
  17260. if (this.meshes[index].name === name) {
  17261. return this.meshes[index];
  17262. }
  17263. }
  17264. return null;
  17265. };
  17266. Scene.prototype.getSoundByName = function (name) {
  17267. var index;
  17268. if (BABYLON.AudioEngine) {
  17269. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17270. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17271. return this.mainSoundTrack.soundCollection[index];
  17272. }
  17273. }
  17274. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17275. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17276. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17277. return this.soundTracks[sdIndex].soundCollection[index];
  17278. }
  17279. }
  17280. }
  17281. }
  17282. return null;
  17283. };
  17284. Scene.prototype.getLastSkeletonByID = function (id) {
  17285. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17286. if (this.skeletons[index].id === id) {
  17287. return this.skeletons[index];
  17288. }
  17289. }
  17290. return null;
  17291. };
  17292. Scene.prototype.getSkeletonById = function (id) {
  17293. for (var index = 0; index < this.skeletons.length; index++) {
  17294. if (this.skeletons[index].id === id) {
  17295. return this.skeletons[index];
  17296. }
  17297. }
  17298. return null;
  17299. };
  17300. Scene.prototype.getSkeletonByName = function (name) {
  17301. for (var index = 0; index < this.skeletons.length; index++) {
  17302. if (this.skeletons[index].name === name) {
  17303. return this.skeletons[index];
  17304. }
  17305. }
  17306. return null;
  17307. };
  17308. Scene.prototype.getMorphTargetManagerById = function (id) {
  17309. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17310. if (this.morphTargetManagers[index].uniqueId === id) {
  17311. return this.morphTargetManagers[index];
  17312. }
  17313. }
  17314. return null;
  17315. };
  17316. Scene.prototype.isActiveMesh = function (mesh) {
  17317. return (this._activeMeshes.indexOf(mesh) !== -1);
  17318. };
  17319. /**
  17320. * Return a the first highlight layer of the scene with a given name.
  17321. * @param name The name of the highlight layer to look for.
  17322. * @return The highlight layer if found otherwise null.
  17323. */
  17324. Scene.prototype.getHighlightLayerByName = function (name) {
  17325. for (var index = 0; index < this.highlightLayers.length; index++) {
  17326. if (this.highlightLayers[index].name === name) {
  17327. return this.highlightLayers[index];
  17328. }
  17329. }
  17330. return null;
  17331. };
  17332. Object.defineProperty(Scene.prototype, "uid", {
  17333. /**
  17334. * Return a unique id as a string which can serve as an identifier for the scene
  17335. */
  17336. get: function () {
  17337. if (!this._uid) {
  17338. this._uid = BABYLON.Tools.RandomId();
  17339. }
  17340. return this._uid;
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. /**
  17346. * Add an externaly attached data from its key.
  17347. * This method call will fail and return false, if such key already exists.
  17348. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17349. * @param key the unique key that identifies the data
  17350. * @param data the data object to associate to the key for this Engine instance
  17351. * @return true if no such key were already present and the data was added successfully, false otherwise
  17352. */
  17353. Scene.prototype.addExternalData = function (key, data) {
  17354. if (!this._externalData) {
  17355. this._externalData = new BABYLON.StringDictionary();
  17356. }
  17357. return this._externalData.add(key, data);
  17358. };
  17359. /**
  17360. * Get an externaly attached data from its key
  17361. * @param key the unique key that identifies the data
  17362. * @return the associated data, if present (can be null), or undefined if not present
  17363. */
  17364. Scene.prototype.getExternalData = function (key) {
  17365. if (!this._externalData) {
  17366. return null;
  17367. }
  17368. return this._externalData.get(key);
  17369. };
  17370. /**
  17371. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17372. * @param key the unique key that identifies the data
  17373. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17374. * @return the associated data, can be null if the factory returned null.
  17375. */
  17376. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17377. if (!this._externalData) {
  17378. this._externalData = new BABYLON.StringDictionary();
  17379. }
  17380. return this._externalData.getOrAddWithFactory(key, factory);
  17381. };
  17382. /**
  17383. * Remove an externaly attached data from the Engine instance
  17384. * @param key the unique key that identifies the data
  17385. * @return true if the data was successfully removed, false if it doesn't exist
  17386. */
  17387. Scene.prototype.removeExternalData = function (key) {
  17388. return this._externalData.remove(key);
  17389. };
  17390. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17391. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17392. var material = subMesh.getMaterial();
  17393. if (mesh.showSubMeshesBoundingBox) {
  17394. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17395. }
  17396. if (material) {
  17397. // Render targets
  17398. if (material.getRenderTargetTextures) {
  17399. if (this._processedMaterials.indexOf(material) === -1) {
  17400. this._processedMaterials.push(material);
  17401. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17402. }
  17403. }
  17404. // Dispatch
  17405. this._activeIndices.addCount(subMesh.indexCount, false);
  17406. this._renderingManager.dispatch(subMesh);
  17407. }
  17408. }
  17409. };
  17410. Scene.prototype._isInIntermediateRendering = function () {
  17411. return this._intermediateRendering;
  17412. };
  17413. Scene.prototype._evaluateActiveMeshes = function () {
  17414. this.activeCamera._activeMeshes.reset();
  17415. this._activeMeshes.reset();
  17416. this._renderingManager.reset();
  17417. this._processedMaterials.reset();
  17418. this._activeParticleSystems.reset();
  17419. this._activeSkeletons.reset();
  17420. this._softwareSkinnedMeshes.reset();
  17421. if (this._boundingBoxRenderer) {
  17422. this._boundingBoxRenderer.reset();
  17423. }
  17424. // Meshes
  17425. var meshes;
  17426. var len;
  17427. if (this._selectionOctree) {
  17428. var selection = this._selectionOctree.select(this._frustumPlanes);
  17429. meshes = selection.data;
  17430. len = selection.length;
  17431. }
  17432. else {
  17433. len = this.meshes.length;
  17434. meshes = this.meshes;
  17435. }
  17436. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17437. var mesh = meshes[meshIndex];
  17438. if (mesh.isBlocked) {
  17439. continue;
  17440. }
  17441. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17442. if (!mesh.isReady() || !mesh.isEnabled()) {
  17443. continue;
  17444. }
  17445. mesh.computeWorldMatrix();
  17446. // Intersections
  17447. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17448. this._meshesForIntersections.pushNoDuplicate(mesh);
  17449. }
  17450. // Switch to current LOD
  17451. var meshLOD = mesh.getLOD(this.activeCamera);
  17452. if (!meshLOD) {
  17453. continue;
  17454. }
  17455. mesh._preActivate();
  17456. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17457. this._activeMeshes.push(mesh);
  17458. this.activeCamera._activeMeshes.push(mesh);
  17459. mesh._activate(this._renderId);
  17460. this._activeMesh(mesh, meshLOD);
  17461. }
  17462. }
  17463. // Particle systems
  17464. this._particlesDuration.beginMonitoring();
  17465. var beforeParticlesDate = BABYLON.Tools.Now;
  17466. if (this.particlesEnabled) {
  17467. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17468. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17469. var particleSystem = this.particleSystems[particleIndex];
  17470. if (!particleSystem.isStarted()) {
  17471. continue;
  17472. }
  17473. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17474. this._activeParticleSystems.push(particleSystem);
  17475. particleSystem.animate();
  17476. this._renderingManager.dispatchParticles(particleSystem);
  17477. }
  17478. }
  17479. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17480. }
  17481. this._particlesDuration.endMonitoring(false);
  17482. };
  17483. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17484. if (mesh.skeleton && this.skeletonsEnabled) {
  17485. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17486. mesh.skeleton.prepare();
  17487. }
  17488. if (!mesh.computeBonesUsingShaders) {
  17489. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17490. }
  17491. }
  17492. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17493. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17494. }
  17495. if (mesh && mesh.subMeshes) {
  17496. // Submeshes Octrees
  17497. var len;
  17498. var subMeshes;
  17499. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17500. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17501. len = intersections.length;
  17502. subMeshes = intersections.data;
  17503. }
  17504. else {
  17505. subMeshes = mesh.subMeshes;
  17506. len = subMeshes.length;
  17507. }
  17508. for (var subIndex = 0; subIndex < len; subIndex++) {
  17509. var subMesh = subMeshes[subIndex];
  17510. this._evaluateSubMesh(subMesh, mesh);
  17511. }
  17512. }
  17513. };
  17514. Scene.prototype.updateTransformMatrix = function (force) {
  17515. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17516. };
  17517. Scene.prototype._renderForCamera = function (camera) {
  17518. var engine = this._engine;
  17519. var startTime = BABYLON.Tools.Now;
  17520. this.activeCamera = camera;
  17521. if (!this.activeCamera)
  17522. throw new Error("Active camera not set");
  17523. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17524. // Viewport
  17525. engine.setViewport(this.activeCamera.viewport);
  17526. // Camera
  17527. this.resetCachedMaterial();
  17528. this._renderId++;
  17529. this.updateTransformMatrix();
  17530. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17531. // Meshes
  17532. this._evaluateActiveMeshesDuration.beginMonitoring();
  17533. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17534. this._evaluateActiveMeshes();
  17535. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17536. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17537. // Software skinning
  17538. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17539. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17540. mesh.applySkeleton(mesh.skeleton);
  17541. }
  17542. // Render targets
  17543. this._renderTargetsDuration.beginMonitoring();
  17544. var needsRestoreFrameBuffer = false;
  17545. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17546. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17547. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17548. }
  17549. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17550. this._intermediateRendering = true;
  17551. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17552. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17553. var renderTarget = this._renderTargets.data[renderIndex];
  17554. if (renderTarget._shouldRender()) {
  17555. this._renderId++;
  17556. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17557. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17558. }
  17559. }
  17560. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17561. this._intermediateRendering = false;
  17562. this._renderId++;
  17563. needsRestoreFrameBuffer = true; // Restore back buffer
  17564. }
  17565. // Render HighlightLayer Texture
  17566. var stencilState = this._engine.getStencilBuffer();
  17567. var renderhighlights = false;
  17568. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17569. this._intermediateRendering = true;
  17570. for (var i = 0; i < this.highlightLayers.length; i++) {
  17571. var highlightLayer = this.highlightLayers[i];
  17572. if (highlightLayer.shouldRender() &&
  17573. (!highlightLayer.camera ||
  17574. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17575. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17576. renderhighlights = true;
  17577. var renderTarget = highlightLayer._mainTexture;
  17578. if (renderTarget._shouldRender()) {
  17579. this._renderId++;
  17580. renderTarget.render(false, false);
  17581. needsRestoreFrameBuffer = true;
  17582. }
  17583. }
  17584. }
  17585. this._intermediateRendering = false;
  17586. this._renderId++;
  17587. }
  17588. if (needsRestoreFrameBuffer) {
  17589. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17590. }
  17591. this._renderTargetsDuration.endMonitoring(false);
  17592. // Prepare Frame
  17593. this.postProcessManager._prepareFrame();
  17594. this._renderDuration.beginMonitoring();
  17595. // Backgrounds
  17596. var layerIndex;
  17597. var layer;
  17598. if (this.layers.length) {
  17599. engine.setDepthBuffer(false);
  17600. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17601. layer = this.layers[layerIndex];
  17602. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17603. layer.render();
  17604. }
  17605. }
  17606. engine.setDepthBuffer(true);
  17607. }
  17608. // Render
  17609. BABYLON.Tools.StartPerformanceCounter("Main render");
  17610. // Activate HighlightLayer stencil
  17611. if (renderhighlights) {
  17612. this._engine.setStencilBuffer(true);
  17613. }
  17614. this._renderingManager.render(null, null, true, true);
  17615. // Restore HighlightLayer stencil
  17616. if (renderhighlights) {
  17617. this._engine.setStencilBuffer(stencilState);
  17618. }
  17619. BABYLON.Tools.EndPerformanceCounter("Main render");
  17620. // Bounding boxes
  17621. if (this._boundingBoxRenderer) {
  17622. this._boundingBoxRenderer.render();
  17623. }
  17624. // Lens flares
  17625. if (this.lensFlaresEnabled) {
  17626. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17627. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17628. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17629. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17630. lensFlareSystem.render();
  17631. }
  17632. }
  17633. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17634. }
  17635. // Foregrounds
  17636. if (this.layers.length) {
  17637. engine.setDepthBuffer(false);
  17638. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17639. layer = this.layers[layerIndex];
  17640. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17641. layer.render();
  17642. }
  17643. }
  17644. engine.setDepthBuffer(true);
  17645. }
  17646. // Highlight Layer
  17647. if (renderhighlights) {
  17648. engine.setDepthBuffer(false);
  17649. for (var i = 0; i < this.highlightLayers.length; i++) {
  17650. if (this.highlightLayers[i].shouldRender()) {
  17651. this.highlightLayers[i].render();
  17652. }
  17653. }
  17654. engine.setDepthBuffer(true);
  17655. }
  17656. this._renderDuration.endMonitoring(false);
  17657. // Finalize frame
  17658. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17659. // Update camera
  17660. this.activeCamera._updateFromScene();
  17661. // Reset some special arrays
  17662. this._renderTargets.reset();
  17663. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17664. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17665. };
  17666. Scene.prototype._processSubCameras = function (camera) {
  17667. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17668. this._renderForCamera(camera);
  17669. return;
  17670. }
  17671. // rig cameras
  17672. for (var index = 0; index < camera._rigCameras.length; index++) {
  17673. this._renderForCamera(camera._rigCameras[index]);
  17674. }
  17675. this.activeCamera = camera;
  17676. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17677. // Update camera
  17678. this.activeCamera._updateFromScene();
  17679. };
  17680. Scene.prototype._checkIntersections = function () {
  17681. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17682. var sourceMesh = this._meshesForIntersections.data[index];
  17683. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17684. var action = sourceMesh.actionManager.actions[actionIndex];
  17685. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17686. var parameters = action.getTriggerParameter();
  17687. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17688. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17689. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17690. if (areIntersecting && currentIntersectionInProgress === -1) {
  17691. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17692. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17693. sourceMesh._intersectionsInProgress.push(otherMesh);
  17694. }
  17695. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17696. sourceMesh._intersectionsInProgress.push(otherMesh);
  17697. }
  17698. }
  17699. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17700. //They intersected, and now they don't.
  17701. //is this trigger an exit trigger? execute an event.
  17702. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17703. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17704. }
  17705. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17706. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17707. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17708. }
  17709. }
  17710. }
  17711. }
  17712. }
  17713. };
  17714. Scene.prototype.render = function () {
  17715. if (this.isDisposed) {
  17716. return;
  17717. }
  17718. this._lastFrameDuration.beginMonitoring();
  17719. this._particlesDuration.fetchNewFrame();
  17720. this._spritesDuration.fetchNewFrame();
  17721. this._activeParticles.fetchNewFrame();
  17722. this._renderDuration.fetchNewFrame();
  17723. this._renderTargetsDuration.fetchNewFrame();
  17724. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17725. this._totalVertices.fetchNewFrame();
  17726. this._activeIndices.fetchNewFrame();
  17727. this._activeBones.fetchNewFrame();
  17728. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17729. this._meshesForIntersections.reset();
  17730. this.resetCachedMaterial();
  17731. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17732. // Actions
  17733. if (this.actionManager) {
  17734. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17735. }
  17736. //Simplification Queue
  17737. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17738. this.simplificationQueue.executeNext();
  17739. }
  17740. // Animations
  17741. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17742. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17743. this._animate();
  17744. // Physics
  17745. if (this._physicsEngine) {
  17746. BABYLON.Tools.StartPerformanceCounter("Physics");
  17747. this._physicsEngine._step(deltaTime / 1000.0);
  17748. BABYLON.Tools.EndPerformanceCounter("Physics");
  17749. }
  17750. // Before render
  17751. this.onBeforeRenderObservable.notifyObservers(this);
  17752. // Customs render targets
  17753. this._renderTargetsDuration.beginMonitoring();
  17754. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17755. var engine = this.getEngine();
  17756. var currentActiveCamera = this.activeCamera;
  17757. if (this.renderTargetsEnabled) {
  17758. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17759. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17760. var renderTarget = this.customRenderTargets[customIndex];
  17761. if (renderTarget._shouldRender()) {
  17762. this._renderId++;
  17763. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17764. if (!this.activeCamera)
  17765. throw new Error("Active camera not set");
  17766. // Viewport
  17767. engine.setViewport(this.activeCamera.viewport);
  17768. // Camera
  17769. this.updateTransformMatrix();
  17770. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17771. }
  17772. }
  17773. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17774. this._renderId++;
  17775. }
  17776. // Restore back buffer
  17777. if (this.customRenderTargets.length > 0) {
  17778. engine.restoreDefaultFramebuffer();
  17779. }
  17780. this._renderTargetsDuration.endMonitoring();
  17781. this.activeCamera = currentActiveCamera;
  17782. // Procedural textures
  17783. if (this.proceduralTexturesEnabled) {
  17784. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17785. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17786. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17787. if (proceduralTexture._shouldRender()) {
  17788. proceduralTexture.render();
  17789. }
  17790. }
  17791. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17792. }
  17793. // Clear
  17794. if (this.autoClearDepthAndStencil || this.autoClear) {
  17795. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17796. }
  17797. // Shadows
  17798. if (this.shadowsEnabled) {
  17799. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17800. var light = this.lights[lightIndex];
  17801. var shadowGenerator = light.getShadowGenerator();
  17802. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17803. var shadowMap = shadowGenerator.getShadowMap();
  17804. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17805. this._renderTargets.push(shadowMap);
  17806. }
  17807. }
  17808. }
  17809. }
  17810. // Depth renderer
  17811. if (this._depthRenderer) {
  17812. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17813. }
  17814. // Geometry renderer
  17815. if (this._geometryBufferRenderer) {
  17816. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17817. }
  17818. // RenderPipeline
  17819. if (this._postProcessRenderPipelineManager) {
  17820. this._postProcessRenderPipelineManager.update();
  17821. }
  17822. // Multi-cameras?
  17823. if (this.activeCameras.length > 0) {
  17824. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17825. if (cameraIndex > 0) {
  17826. this._engine.clear(null, false, true, true);
  17827. }
  17828. this._processSubCameras(this.activeCameras[cameraIndex]);
  17829. }
  17830. }
  17831. else {
  17832. if (!this.activeCamera) {
  17833. throw new Error("No camera defined");
  17834. }
  17835. this._processSubCameras(this.activeCamera);
  17836. }
  17837. // Intersection checks
  17838. this._checkIntersections();
  17839. // Update the audio listener attached to the camera
  17840. if (BABYLON.AudioEngine) {
  17841. this._updateAudioParameters();
  17842. }
  17843. // After render
  17844. if (this.afterRender) {
  17845. this.afterRender();
  17846. }
  17847. this.onAfterRenderObservable.notifyObservers(this);
  17848. // Cleaning
  17849. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17850. this._toBeDisposed.data[index].dispose();
  17851. this._toBeDisposed[index] = null;
  17852. }
  17853. this._toBeDisposed.reset();
  17854. if (this.dumpNextRenderTargets) {
  17855. this.dumpNextRenderTargets = false;
  17856. }
  17857. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17858. this._lastFrameDuration.endMonitoring();
  17859. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17860. this._totalLightsCounter.addCount(this.lights.length, true);
  17861. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17862. this._totalTexturesCounter.addCount(this.textures.length, true);
  17863. this._activeBones.addCount(0, true);
  17864. this._activeIndices.addCount(0, true);
  17865. this._activeParticles.addCount(0, true);
  17866. };
  17867. Scene.prototype._updateAudioParameters = function () {
  17868. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17869. return;
  17870. }
  17871. var listeningCamera;
  17872. var audioEngine = BABYLON.Engine.audioEngine;
  17873. if (this.activeCameras.length > 0) {
  17874. listeningCamera = this.activeCameras[0];
  17875. }
  17876. else {
  17877. listeningCamera = this.activeCamera;
  17878. }
  17879. if (listeningCamera && audioEngine.canUseWebAudio) {
  17880. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17881. // for VR cameras
  17882. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  17883. listeningCamera = listeningCamera.rigCameras[0];
  17884. }
  17885. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17886. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17887. cameraDirection.normalize();
  17888. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17889. var i;
  17890. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17891. var sound = this.mainSoundTrack.soundCollection[i];
  17892. if (sound.useCustomAttenuation) {
  17893. sound.updateDistanceFromListener();
  17894. }
  17895. }
  17896. for (i = 0; i < this.soundTracks.length; i++) {
  17897. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17898. sound = this.soundTracks[i].soundCollection[j];
  17899. if (sound.useCustomAttenuation) {
  17900. sound.updateDistanceFromListener();
  17901. }
  17902. }
  17903. }
  17904. }
  17905. };
  17906. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17907. // Audio
  17908. get: function () {
  17909. return this._audioEnabled;
  17910. },
  17911. set: function (value) {
  17912. this._audioEnabled = value;
  17913. if (BABYLON.AudioEngine) {
  17914. if (this._audioEnabled) {
  17915. this._enableAudio();
  17916. }
  17917. else {
  17918. this._disableAudio();
  17919. }
  17920. }
  17921. },
  17922. enumerable: true,
  17923. configurable: true
  17924. });
  17925. Scene.prototype._disableAudio = function () {
  17926. var i;
  17927. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17928. this.mainSoundTrack.soundCollection[i].pause();
  17929. }
  17930. for (i = 0; i < this.soundTracks.length; i++) {
  17931. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17932. this.soundTracks[i].soundCollection[j].pause();
  17933. }
  17934. }
  17935. };
  17936. Scene.prototype._enableAudio = function () {
  17937. var i;
  17938. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17939. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17940. this.mainSoundTrack.soundCollection[i].play();
  17941. }
  17942. }
  17943. for (i = 0; i < this.soundTracks.length; i++) {
  17944. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17945. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17946. this.soundTracks[i].soundCollection[j].play();
  17947. }
  17948. }
  17949. }
  17950. };
  17951. Object.defineProperty(Scene.prototype, "headphone", {
  17952. get: function () {
  17953. return this._headphone;
  17954. },
  17955. set: function (value) {
  17956. this._headphone = value;
  17957. if (BABYLON.AudioEngine) {
  17958. if (this._headphone) {
  17959. this._switchAudioModeForHeadphones();
  17960. }
  17961. else {
  17962. this._switchAudioModeForNormalSpeakers();
  17963. }
  17964. }
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Scene.prototype._switchAudioModeForHeadphones = function () {
  17970. this.mainSoundTrack.switchPanningModelToHRTF();
  17971. for (var i = 0; i < this.soundTracks.length; i++) {
  17972. this.soundTracks[i].switchPanningModelToHRTF();
  17973. }
  17974. };
  17975. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17976. this.mainSoundTrack.switchPanningModelToEqualPower();
  17977. for (var i = 0; i < this.soundTracks.length; i++) {
  17978. this.soundTracks[i].switchPanningModelToEqualPower();
  17979. }
  17980. };
  17981. Scene.prototype.enableDepthRenderer = function () {
  17982. if (this._depthRenderer) {
  17983. return this._depthRenderer;
  17984. }
  17985. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17986. return this._depthRenderer;
  17987. };
  17988. Scene.prototype.disableDepthRenderer = function () {
  17989. if (!this._depthRenderer) {
  17990. return;
  17991. }
  17992. this._depthRenderer.dispose();
  17993. this._depthRenderer = null;
  17994. };
  17995. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17996. if (ratio === void 0) { ratio = 1; }
  17997. if (this._geometryBufferRenderer) {
  17998. return this._geometryBufferRenderer;
  17999. }
  18000. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18001. if (!this._geometryBufferRenderer.isSupported) {
  18002. this._geometryBufferRenderer = null;
  18003. }
  18004. return this._geometryBufferRenderer;
  18005. };
  18006. Scene.prototype.disableGeometryBufferRenderer = function () {
  18007. if (!this._geometryBufferRenderer) {
  18008. return;
  18009. }
  18010. this._geometryBufferRenderer.dispose();
  18011. this._geometryBufferRenderer = null;
  18012. };
  18013. Scene.prototype.freezeMaterials = function () {
  18014. for (var i = 0; i < this.materials.length; i++) {
  18015. this.materials[i].freeze();
  18016. }
  18017. };
  18018. Scene.prototype.unfreezeMaterials = function () {
  18019. for (var i = 0; i < this.materials.length; i++) {
  18020. this.materials[i].unfreeze();
  18021. }
  18022. };
  18023. Scene.prototype.dispose = function () {
  18024. this.beforeRender = null;
  18025. this.afterRender = null;
  18026. this.skeletons = [];
  18027. this.morphTargetManagers = [];
  18028. this.importedMeshesFiles = new Array();
  18029. if (this._depthRenderer) {
  18030. this._depthRenderer.dispose();
  18031. }
  18032. // Smart arrays
  18033. if (this.activeCamera) {
  18034. this.activeCamera._activeMeshes.dispose();
  18035. this.activeCamera = null;
  18036. }
  18037. this._activeMeshes.dispose();
  18038. this._renderingManager.dispose();
  18039. this._processedMaterials.dispose();
  18040. this._activeParticleSystems.dispose();
  18041. this._activeSkeletons.dispose();
  18042. this._softwareSkinnedMeshes.dispose();
  18043. if (this._boundingBoxRenderer) {
  18044. this._boundingBoxRenderer.dispose();
  18045. }
  18046. this._meshesForIntersections.dispose();
  18047. this._toBeDisposed.dispose();
  18048. // Debug layer
  18049. if (this._debugLayer) {
  18050. this._debugLayer.hide();
  18051. }
  18052. // Events
  18053. this.onDisposeObservable.notifyObservers(this);
  18054. this.onDisposeObservable.clear();
  18055. this.onBeforeRenderObservable.clear();
  18056. this.onAfterRenderObservable.clear();
  18057. this.detachControl();
  18058. // Release sounds & sounds tracks
  18059. if (BABYLON.AudioEngine) {
  18060. this.disposeSounds();
  18061. }
  18062. // Detach cameras
  18063. var canvas = this._engine.getRenderingCanvas();
  18064. var index;
  18065. for (index = 0; index < this.cameras.length; index++) {
  18066. this.cameras[index].detachControl(canvas);
  18067. }
  18068. // Release lights
  18069. while (this.lights.length) {
  18070. this.lights[0].dispose();
  18071. }
  18072. // Release meshes
  18073. while (this.meshes.length) {
  18074. this.meshes[0].dispose(true);
  18075. }
  18076. // Release cameras
  18077. while (this.cameras.length) {
  18078. this.cameras[0].dispose();
  18079. }
  18080. // Release materials
  18081. while (this.materials.length) {
  18082. this.materials[0].dispose();
  18083. }
  18084. // Release particles
  18085. while (this.particleSystems.length) {
  18086. this.particleSystems[0].dispose();
  18087. }
  18088. // Release sprites
  18089. while (this.spriteManagers.length) {
  18090. this.spriteManagers[0].dispose();
  18091. }
  18092. // Release layers
  18093. while (this.layers.length) {
  18094. this.layers[0].dispose();
  18095. }
  18096. while (this.highlightLayers.length) {
  18097. this.highlightLayers[0].dispose();
  18098. }
  18099. // Release textures
  18100. while (this.textures.length) {
  18101. this.textures[0].dispose();
  18102. }
  18103. // Release UBO
  18104. this._sceneUbo.dispose();
  18105. // Post-processes
  18106. this.postProcessManager.dispose();
  18107. // Physics
  18108. if (this._physicsEngine) {
  18109. this.disablePhysicsEngine();
  18110. }
  18111. // Remove from engine
  18112. index = this._engine.scenes.indexOf(this);
  18113. if (index > -1) {
  18114. this._engine.scenes.splice(index, 1);
  18115. }
  18116. this._engine.wipeCaches();
  18117. this._engine = null;
  18118. };
  18119. Object.defineProperty(Scene.prototype, "isDisposed", {
  18120. get: function () {
  18121. return !this._engine;
  18122. },
  18123. enumerable: true,
  18124. configurable: true
  18125. });
  18126. // Release sounds & sounds tracks
  18127. Scene.prototype.disposeSounds = function () {
  18128. this.mainSoundTrack.dispose();
  18129. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18130. this.soundTracks[scIndex].dispose();
  18131. }
  18132. };
  18133. // Octrees
  18134. Scene.prototype.getWorldExtends = function () {
  18135. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18136. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18137. for (var index = 0; index < this.meshes.length; index++) {
  18138. var mesh = this.meshes[index];
  18139. mesh.computeWorldMatrix(true);
  18140. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18141. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18142. BABYLON.Tools.CheckExtends(minBox, min, max);
  18143. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18144. }
  18145. return {
  18146. min: min,
  18147. max: max
  18148. };
  18149. };
  18150. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18151. if (maxCapacity === void 0) { maxCapacity = 64; }
  18152. if (maxDepth === void 0) { maxDepth = 2; }
  18153. if (!this._selectionOctree) {
  18154. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18155. }
  18156. var worldExtends = this.getWorldExtends();
  18157. // Update octree
  18158. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18159. return this._selectionOctree;
  18160. };
  18161. // Picking
  18162. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18163. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18164. var engine = this._engine;
  18165. if (!camera) {
  18166. if (!this.activeCamera)
  18167. throw new Error("Active camera not set");
  18168. camera = this.activeCamera;
  18169. }
  18170. var cameraViewport = camera.viewport;
  18171. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18172. // Moving coordinates to local viewport world
  18173. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18174. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18175. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18176. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18177. };
  18178. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18179. if (!BABYLON.PickingInfo) {
  18180. return null;
  18181. }
  18182. var engine = this._engine;
  18183. if (!camera) {
  18184. if (!this.activeCamera)
  18185. throw new Error("Active camera not set");
  18186. camera = this.activeCamera;
  18187. }
  18188. var cameraViewport = camera.viewport;
  18189. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18190. var identity = BABYLON.Matrix.Identity();
  18191. // Moving coordinates to local viewport world
  18192. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18193. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18194. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18195. };
  18196. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18197. if (!BABYLON.PickingInfo) {
  18198. return null;
  18199. }
  18200. var pickingInfo = null;
  18201. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18202. var mesh = this.meshes[meshIndex];
  18203. if (predicate) {
  18204. if (!predicate(mesh)) {
  18205. continue;
  18206. }
  18207. }
  18208. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18209. continue;
  18210. }
  18211. var world = mesh.getWorldMatrix();
  18212. var ray = rayFunction(world);
  18213. var result = mesh.intersects(ray, fastCheck);
  18214. if (!result || !result.hit)
  18215. continue;
  18216. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18217. continue;
  18218. pickingInfo = result;
  18219. if (fastCheck) {
  18220. break;
  18221. }
  18222. }
  18223. return pickingInfo || new BABYLON.PickingInfo();
  18224. };
  18225. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18226. if (!BABYLON.PickingInfo) {
  18227. return null;
  18228. }
  18229. var pickingInfos = new Array();
  18230. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18231. var mesh = this.meshes[meshIndex];
  18232. if (predicate) {
  18233. if (!predicate(mesh)) {
  18234. continue;
  18235. }
  18236. }
  18237. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18238. continue;
  18239. }
  18240. var world = mesh.getWorldMatrix();
  18241. var ray = rayFunction(world);
  18242. var result = mesh.intersects(ray, false);
  18243. if (!result || !result.hit)
  18244. continue;
  18245. pickingInfos.push(result);
  18246. }
  18247. return pickingInfos;
  18248. };
  18249. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18250. if (!BABYLON.PickingInfo) {
  18251. return null;
  18252. }
  18253. var pickingInfo = null;
  18254. camera = camera || this.activeCamera;
  18255. if (this.spriteManagers.length > 0) {
  18256. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18257. var spriteManager = this.spriteManagers[spriteIndex];
  18258. if (!spriteManager.isPickable) {
  18259. continue;
  18260. }
  18261. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18262. if (!result || !result.hit)
  18263. continue;
  18264. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18265. continue;
  18266. pickingInfo = result;
  18267. if (fastCheck) {
  18268. break;
  18269. }
  18270. }
  18271. }
  18272. return pickingInfo || new BABYLON.PickingInfo();
  18273. };
  18274. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18275. /// <param name="x">X position on screen</param>
  18276. /// <param name="y">Y position on screen</param>
  18277. /// <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>
  18278. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18279. /// <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>
  18280. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18281. var _this = this;
  18282. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18283. };
  18284. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18285. /// <param name="x">X position on screen</param>
  18286. /// <param name="y">Y position on screen</param>
  18287. /// <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>
  18288. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18289. /// <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>
  18290. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18291. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18292. };
  18293. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18294. var _this = this;
  18295. return this._internalPick(function (world) {
  18296. if (!_this._pickWithRayInverseMatrix) {
  18297. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18298. }
  18299. world.invertToRef(_this._pickWithRayInverseMatrix);
  18300. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18301. }, predicate, fastCheck);
  18302. };
  18303. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18304. /// <param name="x">X position on screen</param>
  18305. /// <param name="y">Y position on screen</param>
  18306. /// <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>
  18307. /// <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>
  18308. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18309. var _this = this;
  18310. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18311. };
  18312. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18313. /// <param name="ray">Ray to use</param>
  18314. /// <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>
  18315. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18316. var _this = this;
  18317. return this._internalMultiPick(function (world) {
  18318. if (!_this._pickWithRayInverseMatrix) {
  18319. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18320. }
  18321. world.invertToRef(_this._pickWithRayInverseMatrix);
  18322. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18323. }, predicate);
  18324. };
  18325. Scene.prototype.setPointerOverMesh = function (mesh) {
  18326. if (this._pointerOverMesh === mesh) {
  18327. return;
  18328. }
  18329. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18330. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18331. }
  18332. this._pointerOverMesh = mesh;
  18333. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18334. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18335. }
  18336. };
  18337. Scene.prototype.getPointerOverMesh = function () {
  18338. return this._pointerOverMesh;
  18339. };
  18340. Scene.prototype.setPointerOverSprite = function (sprite) {
  18341. if (this._pointerOverSprite === sprite) {
  18342. return;
  18343. }
  18344. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18345. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18346. }
  18347. this._pointerOverSprite = sprite;
  18348. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18349. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18350. }
  18351. };
  18352. Scene.prototype.getPointerOverSprite = function () {
  18353. return this._pointerOverSprite;
  18354. };
  18355. // Physics
  18356. Scene.prototype.getPhysicsEngine = function () {
  18357. return this._physicsEngine;
  18358. };
  18359. /**
  18360. * Enables physics to the current scene
  18361. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18362. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18363. * @return {boolean} was the physics engine initialized
  18364. */
  18365. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18366. if (this._physicsEngine) {
  18367. return true;
  18368. }
  18369. try {
  18370. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18371. return true;
  18372. }
  18373. catch (e) {
  18374. BABYLON.Tools.Error(e.message);
  18375. return false;
  18376. }
  18377. };
  18378. Scene.prototype.disablePhysicsEngine = function () {
  18379. if (!this._physicsEngine) {
  18380. return;
  18381. }
  18382. this._physicsEngine.dispose();
  18383. this._physicsEngine = undefined;
  18384. };
  18385. Scene.prototype.isPhysicsEnabled = function () {
  18386. return this._physicsEngine !== undefined;
  18387. };
  18388. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18389. var mesh = compound.parts[0].mesh;
  18390. mesh.physicsImpostor.dispose();
  18391. mesh.physicsImpostor = null;
  18392. };
  18393. // Misc.
  18394. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18395. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18396. // Light
  18397. if (this.lights.length === 0) {
  18398. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18399. }
  18400. // Camera
  18401. if (!this.activeCamera) {
  18402. var worldExtends = this.getWorldExtends();
  18403. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18404. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18405. var camera;
  18406. var radius = worldSize.length() * 1.5;
  18407. if (createArcRotateCamera) {
  18408. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18409. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18410. arcRotateCamera.wheelPrecision = 100 / radius;
  18411. camera = arcRotateCamera;
  18412. }
  18413. else {
  18414. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18415. freeCamera.setTarget(worldCenter);
  18416. camera = freeCamera;
  18417. }
  18418. camera.minZ = radius * 0.01;
  18419. camera.maxZ = radius * 100;
  18420. camera.speed = radius * 0.2;
  18421. this.activeCamera = camera;
  18422. }
  18423. };
  18424. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18425. if (pbr === void 0) { pbr = false; }
  18426. if (environmentTexture) {
  18427. this.environmentTexture = environmentTexture;
  18428. }
  18429. if (!this.environmentTexture) {
  18430. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18431. return;
  18432. }
  18433. if (!this.environmentTexture) {
  18434. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18435. return;
  18436. }
  18437. // Skybox
  18438. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18439. if (pbr) {
  18440. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18441. hdrSkyboxMaterial.backFaceCulling = false;
  18442. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18443. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18444. hdrSkyboxMaterial.microSurface = 1.0;
  18445. hdrSkyboxMaterial.disableLighting = true;
  18446. hdrSkybox.infiniteDistance = true;
  18447. hdrSkybox.material = hdrSkyboxMaterial;
  18448. }
  18449. else {
  18450. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18451. skyboxMaterial.backFaceCulling = false;
  18452. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18453. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18454. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18455. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18456. skyboxMaterial.disableLighting = true;
  18457. hdrSkybox.infiniteDistance = true;
  18458. hdrSkybox.material = skyboxMaterial;
  18459. }
  18460. return hdrSkybox;
  18461. };
  18462. // Tags
  18463. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18464. if (tagsQuery === undefined) {
  18465. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18466. return list;
  18467. }
  18468. var listByTags = [];
  18469. forEach = forEach || (function (item) { return; });
  18470. for (var i in list) {
  18471. var item = list[i];
  18472. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18473. listByTags.push(item);
  18474. forEach(item);
  18475. }
  18476. }
  18477. return listByTags;
  18478. };
  18479. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18480. return this._getByTags(this.meshes, tagsQuery, forEach);
  18481. };
  18482. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18483. return this._getByTags(this.cameras, tagsQuery, forEach);
  18484. };
  18485. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18486. return this._getByTags(this.lights, tagsQuery, forEach);
  18487. };
  18488. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18489. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18490. };
  18491. /**
  18492. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18493. * This allowed control for front to back rendering or reversly depending of the special needs.
  18494. *
  18495. * @param renderingGroupId The rendering group id corresponding to its index
  18496. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18497. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18498. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18499. */
  18500. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18501. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18502. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18503. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18504. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18505. };
  18506. /**
  18507. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18508. *
  18509. * @param renderingGroupId The rendering group id corresponding to its index
  18510. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18511. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18512. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18513. */
  18514. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18515. if (depth === void 0) { depth = true; }
  18516. if (stencil === void 0) { stencil = true; }
  18517. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18518. };
  18519. /**
  18520. * Will flag all materials as dirty to trigger new shader compilation
  18521. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18522. */
  18523. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18524. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18525. var material = _a[_i];
  18526. if (predicate && !predicate(material)) {
  18527. continue;
  18528. }
  18529. material.markAsDirty(flag);
  18530. }
  18531. };
  18532. return Scene;
  18533. }());
  18534. // Statics
  18535. Scene._FOGMODE_NONE = 0;
  18536. Scene._FOGMODE_EXP = 1;
  18537. Scene._FOGMODE_EXP2 = 2;
  18538. Scene._FOGMODE_LINEAR = 3;
  18539. Scene.MinDeltaTime = 1.0;
  18540. Scene.MaxDeltaTime = 1000.0;
  18541. Scene.DragMovementThreshold = 10; // in pixels
  18542. Scene.LongPressDelay = 500; // in milliseconds
  18543. Scene.DoubleClickDelay = 300; // in milliseconds
  18544. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18545. BABYLON.Scene = Scene;
  18546. })(BABYLON || (BABYLON = {}));
  18547. //# sourceMappingURL=babylon.scene.js.map
  18548. var BABYLON;
  18549. (function (BABYLON) {
  18550. var Buffer = (function () {
  18551. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18552. if (engine instanceof BABYLON.Mesh) {
  18553. this._engine = engine.getScene().getEngine();
  18554. }
  18555. else {
  18556. this._engine = engine;
  18557. }
  18558. this._updatable = updatable;
  18559. this._data = data;
  18560. this._strideSize = stride;
  18561. if (!postponeInternalCreation) {
  18562. this.create();
  18563. }
  18564. this._instanced = instanced;
  18565. this._instanceDivisor = instanced ? 1 : 0;
  18566. }
  18567. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18568. // a lot of these parameters are ignored as they are overriden by the buffer
  18569. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18570. };
  18571. // Properties
  18572. Buffer.prototype.isUpdatable = function () {
  18573. return this._updatable;
  18574. };
  18575. Buffer.prototype.getData = function () {
  18576. return this._data;
  18577. };
  18578. Buffer.prototype.getBuffer = function () {
  18579. return this._buffer;
  18580. };
  18581. Buffer.prototype.getStrideSize = function () {
  18582. return this._strideSize;
  18583. };
  18584. Buffer.prototype.getIsInstanced = function () {
  18585. return this._instanced;
  18586. };
  18587. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18588. get: function () {
  18589. return this._instanceDivisor;
  18590. },
  18591. set: function (value) {
  18592. this._instanceDivisor = value;
  18593. if (value == 0) {
  18594. this._instanced = false;
  18595. }
  18596. else {
  18597. this._instanced = true;
  18598. }
  18599. },
  18600. enumerable: true,
  18601. configurable: true
  18602. });
  18603. // Methods
  18604. Buffer.prototype.create = function (data) {
  18605. if (!data && this._buffer) {
  18606. return; // nothing to do
  18607. }
  18608. data = data || this._data;
  18609. if (!this._buffer) {
  18610. if (this._updatable) {
  18611. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18612. this._data = data;
  18613. }
  18614. else {
  18615. this._buffer = this._engine.createVertexBuffer(data);
  18616. }
  18617. }
  18618. else if (this._updatable) {
  18619. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18620. this._data = data;
  18621. }
  18622. };
  18623. Buffer.prototype.update = function (data) {
  18624. this.create(data);
  18625. };
  18626. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18627. if (!this._buffer) {
  18628. return;
  18629. }
  18630. if (this._updatable) {
  18631. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18632. this._data = null;
  18633. }
  18634. };
  18635. Buffer.prototype.dispose = function () {
  18636. if (!this._buffer) {
  18637. return;
  18638. }
  18639. if (this._engine._releaseBuffer(this._buffer)) {
  18640. this._buffer = null;
  18641. }
  18642. };
  18643. return Buffer;
  18644. }());
  18645. BABYLON.Buffer = Buffer;
  18646. })(BABYLON || (BABYLON = {}));
  18647. //# sourceMappingURL=babylon.buffer.js.map
  18648. var BABYLON;
  18649. (function (BABYLON) {
  18650. var VertexBuffer = (function () {
  18651. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18652. if (!stride) {
  18653. // Deduce stride from kind
  18654. switch (kind) {
  18655. case VertexBuffer.PositionKind:
  18656. stride = 3;
  18657. break;
  18658. case VertexBuffer.NormalKind:
  18659. stride = 3;
  18660. break;
  18661. case VertexBuffer.UVKind:
  18662. case VertexBuffer.UV2Kind:
  18663. case VertexBuffer.UV3Kind:
  18664. case VertexBuffer.UV4Kind:
  18665. case VertexBuffer.UV5Kind:
  18666. case VertexBuffer.UV6Kind:
  18667. stride = 2;
  18668. break;
  18669. case VertexBuffer.TangentKind:
  18670. case VertexBuffer.ColorKind:
  18671. stride = 4;
  18672. break;
  18673. case VertexBuffer.MatricesIndicesKind:
  18674. case VertexBuffer.MatricesIndicesExtraKind:
  18675. stride = 4;
  18676. break;
  18677. case VertexBuffer.MatricesWeightsKind:
  18678. case VertexBuffer.MatricesWeightsExtraKind:
  18679. stride = 4;
  18680. break;
  18681. }
  18682. }
  18683. if (data instanceof BABYLON.Buffer) {
  18684. if (!stride) {
  18685. stride = data.getStrideSize();
  18686. }
  18687. this._buffer = data;
  18688. this._ownsBuffer = false;
  18689. }
  18690. else {
  18691. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18692. this._ownsBuffer = true;
  18693. }
  18694. this._stride = stride;
  18695. this._offset = offset ? offset : 0;
  18696. this._size = size ? size : stride;
  18697. this._kind = kind;
  18698. }
  18699. /**
  18700. * Returns the kind of the VertexBuffer (string).
  18701. */
  18702. VertexBuffer.prototype.getKind = function () {
  18703. return this._kind;
  18704. };
  18705. // Properties
  18706. /**
  18707. * Boolean : is the VertexBuffer updatable ?
  18708. */
  18709. VertexBuffer.prototype.isUpdatable = function () {
  18710. return this._buffer.isUpdatable();
  18711. };
  18712. /**
  18713. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18714. */
  18715. VertexBuffer.prototype.getData = function () {
  18716. return this._buffer.getData();
  18717. };
  18718. /**
  18719. * Returns the WebGLBuffer associated to the VertexBuffer.
  18720. */
  18721. VertexBuffer.prototype.getBuffer = function () {
  18722. return this._buffer.getBuffer();
  18723. };
  18724. /**
  18725. * Returns the stride of the VertexBuffer (integer).
  18726. */
  18727. VertexBuffer.prototype.getStrideSize = function () {
  18728. return this._stride;
  18729. };
  18730. /**
  18731. * Returns the offset (integer).
  18732. */
  18733. VertexBuffer.prototype.getOffset = function () {
  18734. return this._offset;
  18735. };
  18736. /**
  18737. * Returns the VertexBuffer total size (integer).
  18738. */
  18739. VertexBuffer.prototype.getSize = function () {
  18740. return this._size;
  18741. };
  18742. /**
  18743. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18744. */
  18745. VertexBuffer.prototype.getIsInstanced = function () {
  18746. return this._buffer.getIsInstanced();
  18747. };
  18748. /**
  18749. * Returns the instancing divisor, zero for non-instanced (integer).
  18750. */
  18751. VertexBuffer.prototype.getInstanceDivisor = function () {
  18752. return this._buffer.instanceDivisor;
  18753. };
  18754. // Methods
  18755. /**
  18756. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18757. * Returns the created WebGLBuffer.
  18758. */
  18759. VertexBuffer.prototype.create = function (data) {
  18760. return this._buffer.create(data);
  18761. };
  18762. /**
  18763. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18764. * Returns the updated WebGLBuffer.
  18765. */
  18766. VertexBuffer.prototype.update = function (data) {
  18767. return this._buffer.update(data);
  18768. };
  18769. /**
  18770. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18771. * Returns the directly updated WebGLBuffer.
  18772. */
  18773. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18774. return this._buffer.updateDirectly(data, offset);
  18775. };
  18776. /**
  18777. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18778. */
  18779. VertexBuffer.prototype.dispose = function () {
  18780. if (this._ownsBuffer) {
  18781. this._buffer.dispose();
  18782. }
  18783. };
  18784. Object.defineProperty(VertexBuffer, "PositionKind", {
  18785. get: function () {
  18786. return VertexBuffer._PositionKind;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. Object.defineProperty(VertexBuffer, "NormalKind", {
  18792. get: function () {
  18793. return VertexBuffer._NormalKind;
  18794. },
  18795. enumerable: true,
  18796. configurable: true
  18797. });
  18798. Object.defineProperty(VertexBuffer, "TangentKind", {
  18799. get: function () {
  18800. return VertexBuffer._TangentKind;
  18801. },
  18802. enumerable: true,
  18803. configurable: true
  18804. });
  18805. Object.defineProperty(VertexBuffer, "UVKind", {
  18806. get: function () {
  18807. return VertexBuffer._UVKind;
  18808. },
  18809. enumerable: true,
  18810. configurable: true
  18811. });
  18812. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18813. get: function () {
  18814. return VertexBuffer._UV2Kind;
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18820. get: function () {
  18821. return VertexBuffer._UV3Kind;
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18827. get: function () {
  18828. return VertexBuffer._UV4Kind;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18834. get: function () {
  18835. return VertexBuffer._UV5Kind;
  18836. },
  18837. enumerable: true,
  18838. configurable: true
  18839. });
  18840. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18841. get: function () {
  18842. return VertexBuffer._UV6Kind;
  18843. },
  18844. enumerable: true,
  18845. configurable: true
  18846. });
  18847. Object.defineProperty(VertexBuffer, "ColorKind", {
  18848. get: function () {
  18849. return VertexBuffer._ColorKind;
  18850. },
  18851. enumerable: true,
  18852. configurable: true
  18853. });
  18854. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18855. get: function () {
  18856. return VertexBuffer._MatricesIndicesKind;
  18857. },
  18858. enumerable: true,
  18859. configurable: true
  18860. });
  18861. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18862. get: function () {
  18863. return VertexBuffer._MatricesWeightsKind;
  18864. },
  18865. enumerable: true,
  18866. configurable: true
  18867. });
  18868. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18869. get: function () {
  18870. return VertexBuffer._MatricesIndicesExtraKind;
  18871. },
  18872. enumerable: true,
  18873. configurable: true
  18874. });
  18875. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18876. get: function () {
  18877. return VertexBuffer._MatricesWeightsExtraKind;
  18878. },
  18879. enumerable: true,
  18880. configurable: true
  18881. });
  18882. return VertexBuffer;
  18883. }());
  18884. // Enums
  18885. VertexBuffer._PositionKind = "position";
  18886. VertexBuffer._NormalKind = "normal";
  18887. VertexBuffer._TangentKind = "tangent";
  18888. VertexBuffer._UVKind = "uv";
  18889. VertexBuffer._UV2Kind = "uv2";
  18890. VertexBuffer._UV3Kind = "uv3";
  18891. VertexBuffer._UV4Kind = "uv4";
  18892. VertexBuffer._UV5Kind = "uv5";
  18893. VertexBuffer._UV6Kind = "uv6";
  18894. VertexBuffer._ColorKind = "color";
  18895. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18896. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18897. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18898. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18899. BABYLON.VertexBuffer = VertexBuffer;
  18900. })(BABYLON || (BABYLON = {}));
  18901. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18902. var BABYLON;
  18903. (function (BABYLON) {
  18904. var BaseTexture = (function () {
  18905. function BaseTexture(scene) {
  18906. this._hasAlpha = false;
  18907. this.getAlphaFromRGB = false;
  18908. this.level = 1;
  18909. this.coordinatesIndex = 0;
  18910. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18911. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18912. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18913. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18914. this.isCube = false;
  18915. this.isRenderTarget = false;
  18916. this.animations = new Array();
  18917. /**
  18918. * An event triggered when the texture is disposed.
  18919. * @type {BABYLON.Observable}
  18920. */
  18921. this.onDisposeObservable = new BABYLON.Observable();
  18922. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18923. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18924. this._scene.textures.push(this);
  18925. this._uid = null;
  18926. }
  18927. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18928. get: function () {
  18929. return this._hasAlpha;
  18930. },
  18931. set: function (value) {
  18932. if (this._hasAlpha === value) {
  18933. return;
  18934. }
  18935. this._hasAlpha = value;
  18936. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18937. },
  18938. enumerable: true,
  18939. configurable: true
  18940. });
  18941. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18942. get: function () {
  18943. return this._coordinatesMode;
  18944. },
  18945. set: function (value) {
  18946. if (this._coordinatesMode === value) {
  18947. return;
  18948. }
  18949. this._coordinatesMode = value;
  18950. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18951. },
  18952. enumerable: true,
  18953. configurable: true
  18954. });
  18955. Object.defineProperty(BaseTexture.prototype, "uid", {
  18956. get: function () {
  18957. if (!this._uid) {
  18958. this._uid = BABYLON.Tools.RandomId();
  18959. }
  18960. return this._uid;
  18961. },
  18962. enumerable: true,
  18963. configurable: true
  18964. });
  18965. BaseTexture.prototype.toString = function () {
  18966. return this.name;
  18967. };
  18968. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18969. set: function (callback) {
  18970. if (this._onDisposeObserver) {
  18971. this.onDisposeObservable.remove(this._onDisposeObserver);
  18972. }
  18973. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18974. },
  18975. enumerable: true,
  18976. configurable: true
  18977. });
  18978. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18979. get: function () {
  18980. return true;
  18981. },
  18982. enumerable: true,
  18983. configurable: true
  18984. });
  18985. BaseTexture.prototype.getScene = function () {
  18986. return this._scene;
  18987. };
  18988. BaseTexture.prototype.getTextureMatrix = function () {
  18989. return null;
  18990. };
  18991. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18992. return null;
  18993. };
  18994. BaseTexture.prototype.getInternalTexture = function () {
  18995. return this._texture;
  18996. };
  18997. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18998. return !this.isBlocking || this.isReady();
  18999. };
  19000. BaseTexture.prototype.isReady = function () {
  19001. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19002. this.delayLoad();
  19003. return false;
  19004. }
  19005. if (this._texture) {
  19006. return this._texture.isReady;
  19007. }
  19008. return false;
  19009. };
  19010. BaseTexture.prototype.getSize = function () {
  19011. if (this._texture._width) {
  19012. return new BABYLON.Size(this._texture._width, this._texture._height);
  19013. }
  19014. if (this._texture._size) {
  19015. return new BABYLON.Size(this._texture._size, this._texture._size);
  19016. }
  19017. return BABYLON.Size.Zero();
  19018. };
  19019. BaseTexture.prototype.getBaseSize = function () {
  19020. if (!this.isReady() || !this._texture)
  19021. return BABYLON.Size.Zero();
  19022. if (this._texture._size) {
  19023. return new BABYLON.Size(this._texture._size, this._texture._size);
  19024. }
  19025. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19026. };
  19027. BaseTexture.prototype.scale = function (ratio) {
  19028. };
  19029. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19030. get: function () {
  19031. return false;
  19032. },
  19033. enumerable: true,
  19034. configurable: true
  19035. });
  19036. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19037. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19038. for (var index = 0; index < texturesCache.length; index++) {
  19039. var texturesCacheEntry = texturesCache[index];
  19040. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19041. texturesCache.splice(index, 1);
  19042. return;
  19043. }
  19044. }
  19045. };
  19046. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19047. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19048. for (var index = 0; index < texturesCache.length; index++) {
  19049. var texturesCacheEntry = texturesCache[index];
  19050. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19051. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19052. texturesCacheEntry.references++;
  19053. return texturesCacheEntry;
  19054. }
  19055. }
  19056. }
  19057. return null;
  19058. };
  19059. BaseTexture.prototype.delayLoad = function () {
  19060. };
  19061. BaseTexture.prototype.clone = function () {
  19062. return null;
  19063. };
  19064. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19065. get: function () {
  19066. if (!this._texture) {
  19067. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19068. }
  19069. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19070. },
  19071. enumerable: true,
  19072. configurable: true
  19073. });
  19074. BaseTexture.prototype.readPixels = function (faceIndex, lodIndex) {
  19075. if (faceIndex === void 0) { faceIndex = 0; }
  19076. if (lodIndex === void 0) { lodIndex = 0; }
  19077. if (!this._texture) {
  19078. return null;
  19079. }
  19080. var size = this.getSize();
  19081. var engine = this.getScene().getEngine();
  19082. if (this._texture.isCube) {
  19083. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex, lodIndex);
  19084. }
  19085. return engine._readTexturePixels(this._texture, size.width, size.height, -1, lodIndex);
  19086. };
  19087. BaseTexture.prototype.releaseInternalTexture = function () {
  19088. if (this._texture) {
  19089. this._scene.getEngine().releaseInternalTexture(this._texture);
  19090. delete this._texture;
  19091. }
  19092. };
  19093. BaseTexture.prototype.dispose = function () {
  19094. // Animations
  19095. this.getScene().stopAnimation(this);
  19096. // Remove from scene
  19097. this._scene._removePendingData(this);
  19098. var index = this._scene.textures.indexOf(this);
  19099. if (index >= 0) {
  19100. this._scene.textures.splice(index, 1);
  19101. }
  19102. if (this._texture === undefined) {
  19103. return;
  19104. }
  19105. // Release
  19106. this.releaseInternalTexture();
  19107. // Callback
  19108. this.onDisposeObservable.notifyObservers(this);
  19109. this.onDisposeObservable.clear();
  19110. };
  19111. BaseTexture.prototype.serialize = function () {
  19112. if (!this.name) {
  19113. return null;
  19114. }
  19115. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19116. // Animations
  19117. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19118. return serializationObject;
  19119. };
  19120. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19121. var numReady = 0;
  19122. var _loop_1 = function () {
  19123. texture = textures[i];
  19124. if (texture.isReady()) {
  19125. if (++numReady === textures.length) {
  19126. onLoad();
  19127. }
  19128. }
  19129. else {
  19130. observable = texture.onLoadObservable;
  19131. var callback_1 = function () {
  19132. observable.removeCallback(callback_1);
  19133. if (++numReady === textures.length) {
  19134. onLoad();
  19135. }
  19136. };
  19137. observable.add(callback_1);
  19138. }
  19139. };
  19140. var texture, observable;
  19141. for (var i = 0; i < textures.length; i++) {
  19142. _loop_1();
  19143. }
  19144. };
  19145. return BaseTexture;
  19146. }());
  19147. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19148. __decorate([
  19149. BABYLON.serialize()
  19150. ], BaseTexture.prototype, "name", void 0);
  19151. __decorate([
  19152. BABYLON.serialize("hasAlpha")
  19153. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19154. __decorate([
  19155. BABYLON.serialize()
  19156. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19157. __decorate([
  19158. BABYLON.serialize()
  19159. ], BaseTexture.prototype, "level", void 0);
  19160. __decorate([
  19161. BABYLON.serialize()
  19162. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19163. __decorate([
  19164. BABYLON.serialize("coordinatesMode")
  19165. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19166. __decorate([
  19167. BABYLON.serialize()
  19168. ], BaseTexture.prototype, "wrapU", void 0);
  19169. __decorate([
  19170. BABYLON.serialize()
  19171. ], BaseTexture.prototype, "wrapV", void 0);
  19172. __decorate([
  19173. BABYLON.serialize()
  19174. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19175. __decorate([
  19176. BABYLON.serialize()
  19177. ], BaseTexture.prototype, "isCube", void 0);
  19178. __decorate([
  19179. BABYLON.serialize()
  19180. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19181. BABYLON.BaseTexture = BaseTexture;
  19182. })(BABYLON || (BABYLON = {}));
  19183. //# sourceMappingURL=babylon.baseTexture.js.map
  19184. var BABYLON;
  19185. (function (BABYLON) {
  19186. var Texture = (function (_super) {
  19187. __extends(Texture, _super);
  19188. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19189. if (noMipmap === void 0) { noMipmap = false; }
  19190. if (invertY === void 0) { invertY = true; }
  19191. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19192. if (onLoad === void 0) { onLoad = null; }
  19193. if (onError === void 0) { onError = null; }
  19194. if (buffer === void 0) { buffer = null; }
  19195. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19196. var _this = _super.call(this, scene) || this;
  19197. _this.uOffset = 0;
  19198. _this.vOffset = 0;
  19199. _this.uScale = 1.0;
  19200. _this.vScale = 1.0;
  19201. _this.uAng = 0;
  19202. _this.vAng = 0;
  19203. _this.wAng = 0;
  19204. _this._isBlocking = true;
  19205. _this.name = url;
  19206. _this.url = url;
  19207. _this._noMipmap = noMipmap;
  19208. _this._invertY = invertY;
  19209. _this._samplingMode = samplingMode;
  19210. _this._buffer = buffer;
  19211. _this._deleteBuffer = deleteBuffer;
  19212. _this._format = format;
  19213. scene = _this.getScene();
  19214. var load = function () {
  19215. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19216. _this.onLoadObservable.notifyObservers(_this);
  19217. }
  19218. if (onLoad) {
  19219. onLoad();
  19220. }
  19221. if (!_this.isBlocking) {
  19222. scene.resetCachedMaterial();
  19223. }
  19224. };
  19225. if (!url) {
  19226. _this._delayedOnLoad = load;
  19227. _this._delayedOnError = onError;
  19228. return _this;
  19229. }
  19230. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19231. if (!_this._texture) {
  19232. if (!scene.useDelayedTextureLoading) {
  19233. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19234. if (deleteBuffer) {
  19235. delete _this._buffer;
  19236. }
  19237. }
  19238. else {
  19239. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19240. _this._delayedOnLoad = load;
  19241. _this._delayedOnError = onError;
  19242. }
  19243. }
  19244. else {
  19245. if (_this._texture.isReady) {
  19246. BABYLON.Tools.SetImmediate(function () { return load(); });
  19247. }
  19248. else {
  19249. _this._texture.onLoadedCallbacks.push(load);
  19250. }
  19251. }
  19252. return _this;
  19253. }
  19254. Object.defineProperty(Texture.prototype, "noMipmap", {
  19255. get: function () {
  19256. return this._noMipmap;
  19257. },
  19258. enumerable: true,
  19259. configurable: true
  19260. });
  19261. Object.defineProperty(Texture.prototype, "isBlocking", {
  19262. get: function () {
  19263. return this._isBlocking;
  19264. },
  19265. set: function (value) {
  19266. this._isBlocking = value;
  19267. },
  19268. enumerable: true,
  19269. configurable: true
  19270. });
  19271. Texture.prototype.updateURL = function (url) {
  19272. this.url = url;
  19273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19274. this.delayLoad();
  19275. };
  19276. Texture.prototype.delayLoad = function () {
  19277. var _this = this;
  19278. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19279. return;
  19280. }
  19281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19282. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19283. if (!this._texture) {
  19284. 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);
  19285. if (this._deleteBuffer) {
  19286. delete this._buffer;
  19287. }
  19288. }
  19289. else {
  19290. if (this._texture.isReady) {
  19291. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19292. }
  19293. else {
  19294. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19295. }
  19296. }
  19297. };
  19298. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19299. if (!this._texture) {
  19300. return;
  19301. }
  19302. this._samplingMode = samplingMode;
  19303. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19304. };
  19305. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19306. x *= this.uScale;
  19307. y *= this.vScale;
  19308. x -= 0.5 * this.uScale;
  19309. y -= 0.5 * this.vScale;
  19310. z -= 0.5;
  19311. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19312. t.x += 0.5 * this.uScale + this.uOffset;
  19313. t.y += 0.5 * this.vScale + this.vOffset;
  19314. t.z += 0.5;
  19315. };
  19316. Texture.prototype.getTextureMatrix = function () {
  19317. if (this.uOffset === this._cachedUOffset &&
  19318. this.vOffset === this._cachedVOffset &&
  19319. this.uScale === this._cachedUScale &&
  19320. this.vScale === this._cachedVScale &&
  19321. this.uAng === this._cachedUAng &&
  19322. this.vAng === this._cachedVAng &&
  19323. this.wAng === this._cachedWAng) {
  19324. return this._cachedTextureMatrix;
  19325. }
  19326. this._cachedUOffset = this.uOffset;
  19327. this._cachedVOffset = this.vOffset;
  19328. this._cachedUScale = this.uScale;
  19329. this._cachedVScale = this.vScale;
  19330. this._cachedUAng = this.uAng;
  19331. this._cachedVAng = this.vAng;
  19332. this._cachedWAng = this.wAng;
  19333. if (!this._cachedTextureMatrix) {
  19334. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19335. this._rowGenerationMatrix = new BABYLON.Matrix();
  19336. this._t0 = BABYLON.Vector3.Zero();
  19337. this._t1 = BABYLON.Vector3.Zero();
  19338. this._t2 = BABYLON.Vector3.Zero();
  19339. }
  19340. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19341. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19342. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19343. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19344. this._t1.subtractInPlace(this._t0);
  19345. this._t2.subtractInPlace(this._t0);
  19346. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19347. this._cachedTextureMatrix.m[0] = this._t1.x;
  19348. this._cachedTextureMatrix.m[1] = this._t1.y;
  19349. this._cachedTextureMatrix.m[2] = this._t1.z;
  19350. this._cachedTextureMatrix.m[4] = this._t2.x;
  19351. this._cachedTextureMatrix.m[5] = this._t2.y;
  19352. this._cachedTextureMatrix.m[6] = this._t2.z;
  19353. this._cachedTextureMatrix.m[8] = this._t0.x;
  19354. this._cachedTextureMatrix.m[9] = this._t0.y;
  19355. this._cachedTextureMatrix.m[10] = this._t0.z;
  19356. return this._cachedTextureMatrix;
  19357. };
  19358. Texture.prototype.getReflectionTextureMatrix = function () {
  19359. if (this.uOffset === this._cachedUOffset &&
  19360. this.vOffset === this._cachedVOffset &&
  19361. this.uScale === this._cachedUScale &&
  19362. this.vScale === this._cachedVScale &&
  19363. this.coordinatesMode === this._cachedCoordinatesMode) {
  19364. return this._cachedTextureMatrix;
  19365. }
  19366. if (!this._cachedTextureMatrix) {
  19367. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19368. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19369. }
  19370. this._cachedCoordinatesMode = this.coordinatesMode;
  19371. switch (this.coordinatesMode) {
  19372. case Texture.PLANAR_MODE:
  19373. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19374. this._cachedTextureMatrix[0] = this.uScale;
  19375. this._cachedTextureMatrix[5] = this.vScale;
  19376. this._cachedTextureMatrix[12] = this.uOffset;
  19377. this._cachedTextureMatrix[13] = this.vOffset;
  19378. break;
  19379. case Texture.PROJECTION_MODE:
  19380. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19381. this._projectionModeMatrix.m[0] = 0.5;
  19382. this._projectionModeMatrix.m[5] = -0.5;
  19383. this._projectionModeMatrix.m[10] = 0.0;
  19384. this._projectionModeMatrix.m[12] = 0.5;
  19385. this._projectionModeMatrix.m[13] = 0.5;
  19386. this._projectionModeMatrix.m[14] = 1.0;
  19387. this._projectionModeMatrix.m[15] = 1.0;
  19388. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19389. break;
  19390. default:
  19391. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19392. break;
  19393. }
  19394. return this._cachedTextureMatrix;
  19395. };
  19396. Texture.prototype.clone = function () {
  19397. var _this = this;
  19398. return BABYLON.SerializationHelper.Clone(function () {
  19399. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19400. }, this);
  19401. };
  19402. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19403. get: function () {
  19404. if (!this._onLoadObservable) {
  19405. this._onLoadObservable = new BABYLON.Observable();
  19406. }
  19407. return this._onLoadObservable;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. // Statics
  19413. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19414. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19415. if (onLoad === void 0) { onLoad = null; }
  19416. if (onError === void 0) { onError = null; }
  19417. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19418. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19419. };
  19420. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19421. if (parsedTexture.customType) {
  19422. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19423. // Update Sampling Mode
  19424. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19425. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19426. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19427. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19428. }
  19429. }
  19430. return parsedCustomTexture;
  19431. }
  19432. if (parsedTexture.isCube) {
  19433. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19434. }
  19435. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19436. return null;
  19437. }
  19438. var texture = BABYLON.SerializationHelper.Parse(function () {
  19439. if (parsedTexture.mirrorPlane) {
  19440. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19441. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19442. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19443. return mirrorTexture;
  19444. }
  19445. else if (parsedTexture.isRenderTarget) {
  19446. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19447. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19448. return renderTargetTexture;
  19449. }
  19450. else {
  19451. var texture;
  19452. if (parsedTexture.base64String) {
  19453. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19454. }
  19455. else {
  19456. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19457. }
  19458. return texture;
  19459. }
  19460. }, parsedTexture, scene);
  19461. // Update Sampling Mode
  19462. if (parsedTexture.samplingMode) {
  19463. var sampling = parsedTexture.samplingMode;
  19464. if (texture._samplingMode !== sampling) {
  19465. texture.updateSamplingMode(sampling);
  19466. }
  19467. }
  19468. // Animations
  19469. if (parsedTexture.animations) {
  19470. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19471. var parsedAnimation = parsedTexture.animations[animationIndex];
  19472. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19473. }
  19474. }
  19475. return texture;
  19476. };
  19477. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19478. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19479. if (noMipmap === void 0) { noMipmap = false; }
  19480. if (invertY === void 0) { invertY = true; }
  19481. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19482. if (onLoad === void 0) { onLoad = null; }
  19483. if (onError === void 0) { onError = null; }
  19484. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19485. if (name.substr(0, 5) !== "data:") {
  19486. name = "data:" + name;
  19487. }
  19488. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19489. };
  19490. return Texture;
  19491. }(BABYLON.BaseTexture));
  19492. // Constants
  19493. Texture.NEAREST_SAMPLINGMODE = 1;
  19494. Texture.BILINEAR_SAMPLINGMODE = 2;
  19495. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19496. Texture.EXPLICIT_MODE = 0;
  19497. Texture.SPHERICAL_MODE = 1;
  19498. Texture.PLANAR_MODE = 2;
  19499. Texture.CUBIC_MODE = 3;
  19500. Texture.PROJECTION_MODE = 4;
  19501. Texture.SKYBOX_MODE = 5;
  19502. Texture.INVCUBIC_MODE = 6;
  19503. Texture.EQUIRECTANGULAR_MODE = 7;
  19504. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19505. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19506. Texture.CLAMP_ADDRESSMODE = 0;
  19507. Texture.WRAP_ADDRESSMODE = 1;
  19508. Texture.MIRROR_ADDRESSMODE = 2;
  19509. __decorate([
  19510. BABYLON.serialize()
  19511. ], Texture.prototype, "url", void 0);
  19512. __decorate([
  19513. BABYLON.serialize()
  19514. ], Texture.prototype, "uOffset", void 0);
  19515. __decorate([
  19516. BABYLON.serialize()
  19517. ], Texture.prototype, "vOffset", void 0);
  19518. __decorate([
  19519. BABYLON.serialize()
  19520. ], Texture.prototype, "uScale", void 0);
  19521. __decorate([
  19522. BABYLON.serialize()
  19523. ], Texture.prototype, "vScale", void 0);
  19524. __decorate([
  19525. BABYLON.serialize()
  19526. ], Texture.prototype, "uAng", void 0);
  19527. __decorate([
  19528. BABYLON.serialize()
  19529. ], Texture.prototype, "vAng", void 0);
  19530. __decorate([
  19531. BABYLON.serialize()
  19532. ], Texture.prototype, "wAng", void 0);
  19533. __decorate([
  19534. BABYLON.serialize()
  19535. ], Texture.prototype, "isBlocking", null);
  19536. BABYLON.Texture = Texture;
  19537. })(BABYLON || (BABYLON = {}));
  19538. //# sourceMappingURL=babylon.texture.js.map
  19539. var BABYLON;
  19540. (function (BABYLON) {
  19541. var _InstancesBatch = (function () {
  19542. function _InstancesBatch() {
  19543. this.mustReturn = false;
  19544. this.visibleInstances = new Array();
  19545. this.renderSelf = new Array();
  19546. }
  19547. return _InstancesBatch;
  19548. }());
  19549. BABYLON._InstancesBatch = _InstancesBatch;
  19550. var Mesh = (function (_super) {
  19551. __extends(Mesh, _super);
  19552. /**
  19553. * @constructor
  19554. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19555. * @param {Scene} scene The scene to add this mesh to.
  19556. * @param {Node} parent The parent of this mesh, if it has one
  19557. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19558. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19559. * When false, achieved by calling a clone(), also passing False.
  19560. * This will make creation of children, recursive.
  19561. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19562. */
  19563. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19564. if (parent === void 0) { parent = null; }
  19565. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19566. var _this = _super.call(this, name, scene) || this;
  19567. // Events
  19568. /**
  19569. * An event triggered before rendering the mesh
  19570. * @type {BABYLON.Observable}
  19571. */
  19572. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19573. /**
  19574. * An event triggered after rendering the mesh
  19575. * @type {BABYLON.Observable}
  19576. */
  19577. _this.onAfterRenderObservable = new BABYLON.Observable();
  19578. /**
  19579. * An event triggered before drawing the mesh
  19580. * @type {BABYLON.Observable}
  19581. */
  19582. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19583. // Members
  19584. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19585. _this.instances = new Array();
  19586. _this._LODLevels = new Array();
  19587. _this._visibleInstances = {};
  19588. _this._renderIdForInstances = new Array();
  19589. _this._batchCache = new _InstancesBatch();
  19590. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19591. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19592. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19593. // Will be used to save a source mesh reference, If any
  19594. _this._source = null;
  19595. if (source) {
  19596. // Source mesh
  19597. _this._source = source;
  19598. // Geometry
  19599. if (source._geometry) {
  19600. source._geometry.applyToMesh(_this);
  19601. }
  19602. // Deep copy
  19603. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19604. // Parent
  19605. _this.parent = source.parent;
  19606. // Pivot
  19607. _this.setPivotMatrix(source.getPivotMatrix());
  19608. _this.id = name + "." + source.id;
  19609. // Material
  19610. _this.material = source.material;
  19611. var index;
  19612. if (!doNotCloneChildren) {
  19613. // Children
  19614. for (index = 0; index < scene.meshes.length; index++) {
  19615. var mesh = scene.meshes[index];
  19616. if (mesh.parent === source) {
  19617. // doNotCloneChildren is always going to be False
  19618. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19619. }
  19620. }
  19621. }
  19622. // Physics clone
  19623. var physicsEngine = _this.getScene().getPhysicsEngine();
  19624. if (clonePhysicsImpostor && physicsEngine) {
  19625. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19626. if (impostor) {
  19627. _this.physicsImpostor = impostor.clone(_this);
  19628. }
  19629. }
  19630. // Particles
  19631. for (index = 0; index < scene.particleSystems.length; index++) {
  19632. var system = scene.particleSystems[index];
  19633. if (system.emitter === source) {
  19634. system.clone(system.name, _this);
  19635. }
  19636. }
  19637. _this.computeWorldMatrix(true);
  19638. }
  19639. // Parent
  19640. if (parent !== null) {
  19641. _this.parent = parent;
  19642. }
  19643. return _this;
  19644. }
  19645. Object.defineProperty(Mesh, "FRONTSIDE", {
  19646. /**
  19647. * Mesh side orientation : usually the external or front surface
  19648. */
  19649. get: function () {
  19650. return Mesh._FRONTSIDE;
  19651. },
  19652. enumerable: true,
  19653. configurable: true
  19654. });
  19655. Object.defineProperty(Mesh, "BACKSIDE", {
  19656. /**
  19657. * Mesh side orientation : usually the internal or back surface
  19658. */
  19659. get: function () {
  19660. return Mesh._BACKSIDE;
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19666. /**
  19667. * Mesh side orientation : both internal and external or front and back surfaces
  19668. */
  19669. get: function () {
  19670. return Mesh._DOUBLESIDE;
  19671. },
  19672. enumerable: true,
  19673. configurable: true
  19674. });
  19675. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19676. /**
  19677. * Mesh side orientation : by default, `FRONTSIDE`
  19678. */
  19679. get: function () {
  19680. return Mesh._DEFAULTSIDE;
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(Mesh, "NO_CAP", {
  19686. /**
  19687. * Mesh cap setting : no cap
  19688. */
  19689. get: function () {
  19690. return Mesh._NO_CAP;
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. Object.defineProperty(Mesh, "CAP_START", {
  19696. /**
  19697. * Mesh cap setting : one cap at the beginning of the mesh
  19698. */
  19699. get: function () {
  19700. return Mesh._CAP_START;
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(Mesh, "CAP_END", {
  19706. /**
  19707. * Mesh cap setting : one cap at the end of the mesh
  19708. */
  19709. get: function () {
  19710. return Mesh._CAP_END;
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(Mesh, "CAP_ALL", {
  19716. /**
  19717. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19718. */
  19719. get: function () {
  19720. return Mesh._CAP_ALL;
  19721. },
  19722. enumerable: true,
  19723. configurable: true
  19724. });
  19725. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19726. set: function (callback) {
  19727. if (this._onBeforeDrawObserver) {
  19728. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19729. }
  19730. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19736. get: function () {
  19737. return this._morphTargetManager;
  19738. },
  19739. set: function (value) {
  19740. if (this._morphTargetManager === value) {
  19741. return;
  19742. }
  19743. this._morphTargetManager = value;
  19744. this._syncGeometryWithMorphTargetManager();
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(Mesh.prototype, "source", {
  19750. get: function () {
  19751. return this._source;
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. // Methods
  19757. /**
  19758. * Returns the string "Mesh".
  19759. */
  19760. Mesh.prototype.getClassName = function () {
  19761. return "Mesh";
  19762. };
  19763. /**
  19764. * Returns a string.
  19765. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19766. */
  19767. Mesh.prototype.toString = function (fullDetails) {
  19768. var ret = _super.prototype.toString.call(this, fullDetails);
  19769. ret += ", n vertices: " + this.getTotalVertices();
  19770. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19771. if (this.animations) {
  19772. for (var i = 0; i < this.animations.length; i++) {
  19773. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19774. }
  19775. }
  19776. if (fullDetails) {
  19777. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19778. }
  19779. return ret;
  19780. };
  19781. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19782. /**
  19783. * True if the mesh has some Levels Of Details (LOD).
  19784. * Returns a boolean.
  19785. */
  19786. get: function () {
  19787. return this._LODLevels.length > 0;
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Mesh.prototype._sortLODLevels = function () {
  19793. this._LODLevels.sort(function (a, b) {
  19794. if (a.distance < b.distance) {
  19795. return 1;
  19796. }
  19797. if (a.distance > b.distance) {
  19798. return -1;
  19799. }
  19800. return 0;
  19801. });
  19802. };
  19803. /**
  19804. * Add a mesh as LOD level triggered at the given distance.
  19805. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19806. * @param {number} distance The distance from the center of the object to show this level
  19807. * @param {Mesh} mesh The mesh to be added as LOD level
  19808. * @return {Mesh} This mesh (for chaining)
  19809. */
  19810. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19811. if (mesh && mesh._masterMesh) {
  19812. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19813. return this;
  19814. }
  19815. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19816. this._LODLevels.push(level);
  19817. if (mesh) {
  19818. mesh._masterMesh = this;
  19819. }
  19820. this._sortLODLevels();
  19821. return this;
  19822. };
  19823. /**
  19824. * Returns the LOD level mesh at the passed distance or null if not found.
  19825. * It is related to the method `addLODLevel(distance, mesh)`.
  19826. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19827. * Returns an object Mesh or `null`.
  19828. */
  19829. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19830. for (var index = 0; index < this._LODLevels.length; index++) {
  19831. var level = this._LODLevels[index];
  19832. if (level.distance === distance) {
  19833. return level.mesh;
  19834. }
  19835. }
  19836. return null;
  19837. };
  19838. /**
  19839. * Remove a mesh from the LOD array
  19840. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19841. * @param {Mesh} mesh The mesh to be removed.
  19842. * @return {Mesh} This mesh (for chaining)
  19843. */
  19844. Mesh.prototype.removeLODLevel = function (mesh) {
  19845. for (var index = 0; index < this._LODLevels.length; index++) {
  19846. if (this._LODLevels[index].mesh === mesh) {
  19847. this._LODLevels.splice(index, 1);
  19848. if (mesh) {
  19849. mesh._masterMesh = null;
  19850. }
  19851. }
  19852. }
  19853. this._sortLODLevels();
  19854. return this;
  19855. };
  19856. /**
  19857. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19858. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19859. */
  19860. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19861. if (!this._LODLevels || this._LODLevels.length === 0) {
  19862. return this;
  19863. }
  19864. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19865. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19866. if (this.onLODLevelSelection) {
  19867. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19868. }
  19869. return this;
  19870. }
  19871. for (var index = 0; index < this._LODLevels.length; index++) {
  19872. var level = this._LODLevels[index];
  19873. if (level.distance < distanceToCamera) {
  19874. if (level.mesh) {
  19875. level.mesh._preActivate();
  19876. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19877. }
  19878. if (this.onLODLevelSelection) {
  19879. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19880. }
  19881. return level.mesh;
  19882. }
  19883. }
  19884. if (this.onLODLevelSelection) {
  19885. this.onLODLevelSelection(distanceToCamera, this, this);
  19886. }
  19887. return this;
  19888. };
  19889. Object.defineProperty(Mesh.prototype, "geometry", {
  19890. /**
  19891. * Returns the mesh internal Geometry object.
  19892. */
  19893. get: function () {
  19894. return this._geometry;
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. /**
  19900. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19901. */
  19902. Mesh.prototype.getTotalVertices = function () {
  19903. if (!this._geometry) {
  19904. return 0;
  19905. }
  19906. return this._geometry.getTotalVertices();
  19907. };
  19908. /**
  19909. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19910. * 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.
  19911. * You can force the copy with forceCopy === true
  19912. * Returns null if the mesh has no geometry or no vertex buffer.
  19913. * Possible `kind` values :
  19914. * - BABYLON.VertexBuffer.PositionKind
  19915. * - BABYLON.VertexBuffer.UVKind
  19916. * - BABYLON.VertexBuffer.UV2Kind
  19917. * - BABYLON.VertexBuffer.UV3Kind
  19918. * - BABYLON.VertexBuffer.UV4Kind
  19919. * - BABYLON.VertexBuffer.UV5Kind
  19920. * - BABYLON.VertexBuffer.UV6Kind
  19921. * - BABYLON.VertexBuffer.ColorKind
  19922. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19923. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19924. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19925. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19926. */
  19927. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19928. if (!this._geometry) {
  19929. return null;
  19930. }
  19931. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19932. };
  19933. /**
  19934. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19935. * Returns `undefined` if the mesh has no geometry.
  19936. * Possible `kind` values :
  19937. * - BABYLON.VertexBuffer.PositionKind
  19938. * - BABYLON.VertexBuffer.UVKind
  19939. * - BABYLON.VertexBuffer.UV2Kind
  19940. * - BABYLON.VertexBuffer.UV3Kind
  19941. * - BABYLON.VertexBuffer.UV4Kind
  19942. * - BABYLON.VertexBuffer.UV5Kind
  19943. * - BABYLON.VertexBuffer.UV6Kind
  19944. * - BABYLON.VertexBuffer.ColorKind
  19945. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19946. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19947. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19948. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19949. */
  19950. Mesh.prototype.getVertexBuffer = function (kind) {
  19951. if (!this._geometry) {
  19952. return undefined;
  19953. }
  19954. return this._geometry.getVertexBuffer(kind);
  19955. };
  19956. /**
  19957. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19958. * Possible `kind` values :
  19959. * - BABYLON.VertexBuffer.PositionKind
  19960. * - BABYLON.VertexBuffer.UVKind
  19961. * - BABYLON.VertexBuffer.UV2Kind
  19962. * - BABYLON.VertexBuffer.UV3Kind
  19963. * - BABYLON.VertexBuffer.UV4Kind
  19964. * - BABYLON.VertexBuffer.UV5Kind
  19965. * - BABYLON.VertexBuffer.UV6Kind
  19966. * - BABYLON.VertexBuffer.ColorKind
  19967. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19968. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19969. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19970. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19971. */
  19972. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19973. if (!this._geometry) {
  19974. if (this._delayInfo) {
  19975. return this._delayInfo.indexOf(kind) !== -1;
  19976. }
  19977. return false;
  19978. }
  19979. return this._geometry.isVerticesDataPresent(kind);
  19980. };
  19981. /**
  19982. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19983. * Possible `kind` values :
  19984. * - BABYLON.VertexBuffer.PositionKind
  19985. * - BABYLON.VertexBuffer.UVKind
  19986. * - BABYLON.VertexBuffer.UV2Kind
  19987. * - BABYLON.VertexBuffer.UV3Kind
  19988. * - BABYLON.VertexBuffer.UV4Kind
  19989. * - BABYLON.VertexBuffer.UV5Kind
  19990. * - BABYLON.VertexBuffer.UV6Kind
  19991. * - BABYLON.VertexBuffer.ColorKind
  19992. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19993. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19994. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19995. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19996. */
  19997. Mesh.prototype.getVerticesDataKinds = function () {
  19998. if (!this._geometry) {
  19999. var result = [];
  20000. if (this._delayInfo) {
  20001. this._delayInfo.forEach(function (kind, index, array) {
  20002. result.push(kind);
  20003. });
  20004. }
  20005. return result;
  20006. }
  20007. return this._geometry.getVerticesDataKinds();
  20008. };
  20009. /**
  20010. * Returns a positive integer : the total number of indices in this mesh geometry.
  20011. * Returns zero if the mesh has no geometry.
  20012. */
  20013. Mesh.prototype.getTotalIndices = function () {
  20014. if (!this._geometry) {
  20015. return 0;
  20016. }
  20017. return this._geometry.getTotalIndices();
  20018. };
  20019. /**
  20020. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20021. * 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.
  20022. * Returns an empty array if the mesh has no geometry.
  20023. */
  20024. Mesh.prototype.getIndices = function (copyWhenShared) {
  20025. if (!this._geometry) {
  20026. return [];
  20027. }
  20028. return this._geometry.getIndices(copyWhenShared);
  20029. };
  20030. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20031. get: function () {
  20032. return this._masterMesh !== null && this._masterMesh !== undefined;
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. /**
  20038. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20039. */
  20040. Mesh.prototype.isReady = function () {
  20041. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20042. return false;
  20043. }
  20044. return _super.prototype.isReady.call(this);
  20045. };
  20046. /**
  20047. * Boolean : true if the mesh has been disposed.
  20048. */
  20049. Mesh.prototype.isDisposed = function () {
  20050. return this._isDisposed;
  20051. };
  20052. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20053. get: function () {
  20054. return this._sideOrientation;
  20055. },
  20056. /**
  20057. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20058. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20059. */
  20060. set: function (sideO) {
  20061. this._sideOrientation = sideO;
  20062. },
  20063. enumerable: true,
  20064. configurable: true
  20065. });
  20066. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20067. /**
  20068. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20069. * This property is pertinent only for updatable parametric shapes.
  20070. */
  20071. get: function () {
  20072. return this._areNormalsFrozen;
  20073. },
  20074. enumerable: true,
  20075. configurable: true
  20076. });
  20077. /**
  20078. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20079. * It has no effect at all on other shapes.
  20080. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20081. * Returns the Mesh.
  20082. */
  20083. Mesh.prototype.freezeNormals = function () {
  20084. this._areNormalsFrozen = true;
  20085. return this;
  20086. };
  20087. /**
  20088. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20089. * It has no effect at all on other shapes.
  20090. * It reactivates the mesh normals computation if it was previously frozen.
  20091. * Returns the Mesh.
  20092. */
  20093. Mesh.prototype.unfreezeNormals = function () {
  20094. this._areNormalsFrozen = false;
  20095. return this;
  20096. };
  20097. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20098. /**
  20099. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20100. */
  20101. set: function (count) {
  20102. this._overridenInstanceCount = count;
  20103. },
  20104. enumerable: true,
  20105. configurable: true
  20106. });
  20107. // Methods
  20108. Mesh.prototype._preActivate = function () {
  20109. var sceneRenderId = this.getScene().getRenderId();
  20110. if (this._preActivateId === sceneRenderId) {
  20111. return this;
  20112. }
  20113. this._preActivateId = sceneRenderId;
  20114. this._visibleInstances = null;
  20115. return this;
  20116. };
  20117. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20118. if (this._visibleInstances) {
  20119. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20120. }
  20121. return this;
  20122. };
  20123. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20124. if (!this._visibleInstances) {
  20125. this._visibleInstances = {};
  20126. this._visibleInstances.defaultRenderId = renderId;
  20127. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20128. }
  20129. if (!this._visibleInstances[renderId]) {
  20130. this._visibleInstances[renderId] = new Array();
  20131. }
  20132. this._visibleInstances[renderId].push(instance);
  20133. return this;
  20134. };
  20135. /**
  20136. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20137. * This means the mesh underlying bounding box and sphere are recomputed.
  20138. * Returns the Mesh.
  20139. */
  20140. Mesh.prototype.refreshBoundingInfo = function () {
  20141. if (this._boundingInfo.isLocked) {
  20142. return;
  20143. }
  20144. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20145. if (data) {
  20146. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20147. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20148. }
  20149. if (this.subMeshes) {
  20150. for (var index = 0; index < this.subMeshes.length; index++) {
  20151. this.subMeshes[index].refreshBoundingInfo();
  20152. }
  20153. }
  20154. this._updateBoundingInfo();
  20155. return this;
  20156. };
  20157. Mesh.prototype._createGlobalSubMesh = function () {
  20158. var totalVertices = this.getTotalVertices();
  20159. if (!totalVertices || !this.getIndices()) {
  20160. return null;
  20161. }
  20162. this.releaseSubMeshes();
  20163. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20164. };
  20165. Mesh.prototype.subdivide = function (count) {
  20166. if (count < 1) {
  20167. return;
  20168. }
  20169. var totalIndices = this.getTotalIndices();
  20170. var subdivisionSize = (totalIndices / count) | 0;
  20171. var offset = 0;
  20172. // Ensure that subdivisionSize is a multiple of 3
  20173. while (subdivisionSize % 3 !== 0) {
  20174. subdivisionSize++;
  20175. }
  20176. this.releaseSubMeshes();
  20177. for (var index = 0; index < count; index++) {
  20178. if (offset >= totalIndices) {
  20179. break;
  20180. }
  20181. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20182. offset += subdivisionSize;
  20183. }
  20184. this.synchronizeInstances();
  20185. };
  20186. /**
  20187. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20188. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20189. * The `data` are either a numeric array either a Float32Array.
  20190. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20191. * 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).
  20192. * Note that a new underlying VertexBuffer object is created each call.
  20193. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20194. *
  20195. * Possible `kind` values :
  20196. * - BABYLON.VertexBuffer.PositionKind
  20197. * - BABYLON.VertexBuffer.UVKind
  20198. * - BABYLON.VertexBuffer.UV2Kind
  20199. * - BABYLON.VertexBuffer.UV3Kind
  20200. * - BABYLON.VertexBuffer.UV4Kind
  20201. * - BABYLON.VertexBuffer.UV5Kind
  20202. * - BABYLON.VertexBuffer.UV6Kind
  20203. * - BABYLON.VertexBuffer.ColorKind
  20204. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20205. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20206. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20207. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20208. *
  20209. * Returns the Mesh.
  20210. */
  20211. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20212. if (!this._geometry) {
  20213. var vertexData = new BABYLON.VertexData();
  20214. vertexData.set(data, kind);
  20215. var scene = this.getScene();
  20216. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20217. }
  20218. else {
  20219. this._geometry.setVerticesData(kind, data, updatable, stride);
  20220. }
  20221. return this;
  20222. };
  20223. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20224. if (updatable === void 0) { updatable = true; }
  20225. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20226. return;
  20227. }
  20228. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20229. };
  20230. /**
  20231. * Sets the mesh VertexBuffer.
  20232. * Returns the Mesh.
  20233. */
  20234. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20235. if (!this._geometry) {
  20236. var scene = this.getScene();
  20237. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20238. }
  20239. this._geometry.setVerticesBuffer(buffer);
  20240. return this;
  20241. };
  20242. /**
  20243. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20244. * If the mesh has no geometry, it is simply returned as it is.
  20245. * The `data` are either a numeric array either a Float32Array.
  20246. * No new underlying VertexBuffer object is created.
  20247. * 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.
  20248. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20249. *
  20250. * Possible `kind` values :
  20251. * - BABYLON.VertexBuffer.PositionKind
  20252. * - BABYLON.VertexBuffer.UVKind
  20253. * - BABYLON.VertexBuffer.UV2Kind
  20254. * - BABYLON.VertexBuffer.UV3Kind
  20255. * - BABYLON.VertexBuffer.UV4Kind
  20256. * - BABYLON.VertexBuffer.UV5Kind
  20257. * - BABYLON.VertexBuffer.UV6Kind
  20258. * - BABYLON.VertexBuffer.ColorKind
  20259. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20260. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20261. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20262. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20263. *
  20264. * Returns the Mesh.
  20265. */
  20266. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20267. if (!this._geometry) {
  20268. return;
  20269. }
  20270. if (!makeItUnique) {
  20271. this._geometry.updateVerticesData(kind, data, updateExtends);
  20272. }
  20273. else {
  20274. this.makeGeometryUnique();
  20275. this.updateVerticesData(kind, data, updateExtends, false);
  20276. }
  20277. return this;
  20278. };
  20279. /**
  20280. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20281. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20282. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20283. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20284. * Returns the Mesh.
  20285. */
  20286. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20287. if (computeNormals === void 0) { computeNormals = true; }
  20288. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20289. positionFunction(positions);
  20290. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20291. if (computeNormals) {
  20292. var indices = this.getIndices();
  20293. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20294. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20295. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20296. }
  20297. return this;
  20298. };
  20299. /**
  20300. * Creates a un-shared specific occurence of the geometry for the mesh.
  20301. * Returns the Mesh.
  20302. */
  20303. Mesh.prototype.makeGeometryUnique = function () {
  20304. if (!this._geometry) {
  20305. return;
  20306. }
  20307. var oldGeometry = this._geometry;
  20308. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20309. oldGeometry.releaseForMesh(this, true);
  20310. geometry.applyToMesh(this);
  20311. return this;
  20312. };
  20313. /**
  20314. * Sets the mesh indices.
  20315. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20316. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20317. * This method creates a new index buffer each call.
  20318. * Returns the Mesh.
  20319. */
  20320. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20321. if (!this._geometry) {
  20322. var vertexData = new BABYLON.VertexData();
  20323. vertexData.indices = indices;
  20324. var scene = this.getScene();
  20325. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20326. }
  20327. else {
  20328. this._geometry.setIndices(indices, totalVertices);
  20329. }
  20330. return this;
  20331. };
  20332. /**
  20333. * Invert the geometry to move from a right handed system to a left handed one.
  20334. * Returns the Mesh.
  20335. */
  20336. Mesh.prototype.toLeftHanded = function () {
  20337. if (!this._geometry) {
  20338. return;
  20339. }
  20340. this._geometry.toLeftHanded();
  20341. return this;
  20342. };
  20343. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20344. var engine = this.getScene().getEngine();
  20345. // Wireframe
  20346. var indexToBind;
  20347. if (this._unIndexed) {
  20348. indexToBind = null;
  20349. }
  20350. else {
  20351. switch (fillMode) {
  20352. case BABYLON.Material.PointFillMode:
  20353. indexToBind = null;
  20354. break;
  20355. case BABYLON.Material.WireFrameFillMode:
  20356. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20357. break;
  20358. default:
  20359. case BABYLON.Material.TriangleFillMode:
  20360. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20361. break;
  20362. }
  20363. }
  20364. // VBOs
  20365. this._geometry._bind(effect, indexToBind);
  20366. return this;
  20367. };
  20368. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20369. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20370. return this;
  20371. }
  20372. this.onBeforeDrawObservable.notifyObservers(this);
  20373. var engine = this.getScene().getEngine();
  20374. // Draw order
  20375. switch (fillMode) {
  20376. case BABYLON.Material.PointFillMode:
  20377. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20378. break;
  20379. case BABYLON.Material.WireFrameFillMode:
  20380. if (this._unIndexed) {
  20381. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20382. }
  20383. else {
  20384. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20385. }
  20386. break;
  20387. default:
  20388. if (this._unIndexed) {
  20389. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20390. }
  20391. else {
  20392. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20393. }
  20394. }
  20395. return this;
  20396. };
  20397. /**
  20398. * Registers for this mesh a javascript function called just before the rendering process.
  20399. * This function is passed the current mesh.
  20400. * Return the Mesh.
  20401. */
  20402. Mesh.prototype.registerBeforeRender = function (func) {
  20403. this.onBeforeRenderObservable.add(func);
  20404. return this;
  20405. };
  20406. /**
  20407. * Disposes a previously registered javascript function called before the rendering.
  20408. * This function is passed the current mesh.
  20409. * Returns the Mesh.
  20410. */
  20411. Mesh.prototype.unregisterBeforeRender = function (func) {
  20412. this.onBeforeRenderObservable.removeCallback(func);
  20413. return this;
  20414. };
  20415. /**
  20416. * Registers for this mesh a javascript function called just after the rendering is complete.
  20417. * This function is passed the current mesh.
  20418. * Returns the Mesh.
  20419. */
  20420. Mesh.prototype.registerAfterRender = function (func) {
  20421. this.onAfterRenderObservable.add(func);
  20422. return this;
  20423. };
  20424. /**
  20425. * Disposes a previously registered javascript function called after the rendering.
  20426. * This function is passed the current mesh.
  20427. * Return the Mesh.
  20428. */
  20429. Mesh.prototype.unregisterAfterRender = function (func) {
  20430. this.onAfterRenderObservable.removeCallback(func);
  20431. return this;
  20432. };
  20433. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20434. var scene = this.getScene();
  20435. this._batchCache.mustReturn = false;
  20436. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20437. this._batchCache.visibleInstances[subMeshId] = null;
  20438. if (this._visibleInstances) {
  20439. var currentRenderId = scene.getRenderId();
  20440. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20441. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20442. var selfRenderId = this._renderId;
  20443. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20444. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20445. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20446. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20447. }
  20448. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20449. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20450. this._batchCache.mustReturn = true;
  20451. return this._batchCache;
  20452. }
  20453. if (currentRenderId !== selfRenderId) {
  20454. this._batchCache.renderSelf[subMeshId] = false;
  20455. }
  20456. }
  20457. this._renderIdForInstances[subMeshId] = currentRenderId;
  20458. }
  20459. return this._batchCache;
  20460. };
  20461. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20462. var visibleInstances = batch.visibleInstances[subMesh._id];
  20463. var matricesCount = visibleInstances.length + 1;
  20464. var bufferSize = matricesCount * 16 * 4;
  20465. var currentInstancesBufferSize = this._instancesBufferSize;
  20466. var instancesBuffer = this._instancesBuffer;
  20467. while (this._instancesBufferSize < bufferSize) {
  20468. this._instancesBufferSize *= 2;
  20469. }
  20470. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20471. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20472. }
  20473. var offset = 0;
  20474. var instancesCount = 0;
  20475. var world = this.getWorldMatrix();
  20476. if (batch.renderSelf[subMesh._id]) {
  20477. world.copyToArray(this._instancesData, offset);
  20478. offset += 16;
  20479. instancesCount++;
  20480. }
  20481. if (visibleInstances) {
  20482. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20483. var instance = visibleInstances[instanceIndex];
  20484. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20485. offset += 16;
  20486. instancesCount++;
  20487. }
  20488. }
  20489. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20490. if (instancesBuffer) {
  20491. instancesBuffer.dispose();
  20492. }
  20493. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20494. this._instancesBuffer = instancesBuffer;
  20495. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20496. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20497. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20498. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20499. }
  20500. else {
  20501. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20502. }
  20503. this.geometry._bind(effect);
  20504. this._draw(subMesh, fillMode, instancesCount);
  20505. engine.unbindInstanceAttributes();
  20506. return this;
  20507. };
  20508. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20509. var scene = this.getScene();
  20510. var engine = scene.getEngine();
  20511. if (hardwareInstancedRendering) {
  20512. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20513. }
  20514. else {
  20515. if (batch.renderSelf[subMesh._id]) {
  20516. // Draw
  20517. if (onBeforeDraw) {
  20518. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20519. }
  20520. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20521. }
  20522. if (batch.visibleInstances[subMesh._id]) {
  20523. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20524. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20525. // World
  20526. var world = instance.getWorldMatrix();
  20527. if (onBeforeDraw) {
  20528. onBeforeDraw(true, world, effectiveMaterial);
  20529. }
  20530. // Draw
  20531. this._draw(subMesh, fillMode);
  20532. }
  20533. }
  20534. }
  20535. return this;
  20536. };
  20537. /**
  20538. * Triggers the draw call for the mesh.
  20539. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20540. * Returns the Mesh.
  20541. */
  20542. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20543. var scene = this.getScene();
  20544. // Managing instances
  20545. var batch = this._getInstancesRenderList(subMesh._id);
  20546. if (batch.mustReturn) {
  20547. return this;
  20548. }
  20549. // Checking geometry state
  20550. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20551. return this;
  20552. }
  20553. var callbackIndex;
  20554. this.onBeforeRenderObservable.notifyObservers(this);
  20555. var engine = scene.getEngine();
  20556. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20557. // Material
  20558. var effectiveMaterial = subMesh.getMaterial();
  20559. if (!effectiveMaterial) {
  20560. return this;
  20561. }
  20562. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20563. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20564. return this;
  20565. }
  20566. }
  20567. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20568. return this;
  20569. }
  20570. // Alpha mode
  20571. if (enableAlphaMode) {
  20572. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20573. }
  20574. // Outline - step 1
  20575. var savedDepthWrite = engine.getDepthWrite();
  20576. if (this.renderOutline) {
  20577. engine.setDepthWrite(false);
  20578. scene.getOutlineRenderer().render(subMesh, batch);
  20579. engine.setDepthWrite(savedDepthWrite);
  20580. }
  20581. var effect;
  20582. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20583. effect = subMesh.effect;
  20584. }
  20585. else {
  20586. effect = effectiveMaterial.getEffect();
  20587. }
  20588. effectiveMaterial._preBind(effect);
  20589. // Bind
  20590. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20591. this._bind(subMesh, effect, fillMode);
  20592. var world = this.getWorldMatrix();
  20593. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20594. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20595. }
  20596. else {
  20597. effectiveMaterial.bind(world, this);
  20598. }
  20599. // Draw
  20600. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20601. // Unbind
  20602. effectiveMaterial.unbind();
  20603. // Outline - step 2
  20604. if (this.renderOutline && savedDepthWrite) {
  20605. engine.setDepthWrite(true);
  20606. engine.setColorWrite(false);
  20607. scene.getOutlineRenderer().render(subMesh, batch);
  20608. engine.setColorWrite(true);
  20609. }
  20610. // Overlay
  20611. if (this.renderOverlay) {
  20612. var currentMode = engine.getAlphaMode();
  20613. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20614. scene.getOutlineRenderer().render(subMesh, batch, true);
  20615. engine.setAlphaMode(currentMode);
  20616. }
  20617. this.onAfterRenderObservable.notifyObservers(this);
  20618. return this;
  20619. };
  20620. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20621. if (isInstance) {
  20622. effectiveMaterial.bindOnlyWorldMatrix(world);
  20623. }
  20624. return this;
  20625. };
  20626. /**
  20627. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20628. */
  20629. Mesh.prototype.getEmittedParticleSystems = function () {
  20630. var results = new Array();
  20631. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20632. var particleSystem = this.getScene().particleSystems[index];
  20633. if (particleSystem.emitter === this) {
  20634. results.push(particleSystem);
  20635. }
  20636. }
  20637. return results;
  20638. };
  20639. /**
  20640. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20641. */
  20642. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20643. var results = new Array();
  20644. var descendants = this.getDescendants();
  20645. descendants.push(this);
  20646. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20647. var particleSystem = this.getScene().particleSystems[index];
  20648. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20649. results.push(particleSystem);
  20650. }
  20651. }
  20652. return results;
  20653. };
  20654. Mesh.prototype._checkDelayState = function () {
  20655. var scene = this.getScene();
  20656. if (this._geometry) {
  20657. this._geometry.load(scene);
  20658. }
  20659. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20661. this._queueLoad(this, scene);
  20662. }
  20663. return this;
  20664. };
  20665. Mesh.prototype._queueLoad = function (mesh, scene) {
  20666. var _this = this;
  20667. scene._addPendingData(mesh);
  20668. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20669. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20670. if (data instanceof ArrayBuffer) {
  20671. _this._delayLoadingFunction(data, _this);
  20672. }
  20673. else {
  20674. _this._delayLoadingFunction(JSON.parse(data), _this);
  20675. }
  20676. _this.instances.forEach(function (instance) {
  20677. instance._syncSubMeshes();
  20678. });
  20679. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20680. scene._removePendingData(_this);
  20681. }, function () { }, scene.database, getBinaryData);
  20682. return this;
  20683. };
  20684. /**
  20685. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20686. */
  20687. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20688. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20689. return false;
  20690. }
  20691. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20692. return false;
  20693. }
  20694. this._checkDelayState();
  20695. return true;
  20696. };
  20697. /**
  20698. * Sets the mesh material by the material or multiMaterial `id` property.
  20699. * The material `id` is a string identifying the material or the multiMaterial.
  20700. * This method returns the Mesh.
  20701. */
  20702. Mesh.prototype.setMaterialByID = function (id) {
  20703. var materials = this.getScene().materials;
  20704. var index;
  20705. for (index = materials.length - 1; index > -1; index--) {
  20706. if (materials[index].id === id) {
  20707. this.material = materials[index];
  20708. return this;
  20709. }
  20710. }
  20711. // Multi
  20712. var multiMaterials = this.getScene().multiMaterials;
  20713. for (index = multiMaterials.length - 1; index > -1; index--) {
  20714. if (multiMaterials[index].id === id) {
  20715. this.material = multiMaterials[index];
  20716. return this;
  20717. }
  20718. }
  20719. return this;
  20720. };
  20721. /**
  20722. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20723. */
  20724. Mesh.prototype.getAnimatables = function () {
  20725. var results = [];
  20726. if (this.material) {
  20727. results.push(this.material);
  20728. }
  20729. if (this.skeleton) {
  20730. results.push(this.skeleton);
  20731. }
  20732. return results;
  20733. };
  20734. /**
  20735. * Modifies the mesh geometry according to the passed transformation matrix.
  20736. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20737. * The mesh normals are modified accordingly the same transformation.
  20738. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20739. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20740. * Returns the Mesh.
  20741. */
  20742. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20743. // Position
  20744. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20745. return this;
  20746. }
  20747. var submeshes = this.subMeshes.splice(0);
  20748. this._resetPointsArrayCache();
  20749. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20750. var temp = [];
  20751. var index;
  20752. for (index = 0; index < data.length; index += 3) {
  20753. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20754. }
  20755. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20756. // Normals
  20757. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20758. return this;
  20759. }
  20760. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20761. temp = [];
  20762. for (index = 0; index < data.length; index += 3) {
  20763. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20764. }
  20765. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20766. // flip faces?
  20767. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20768. this.flipFaces();
  20769. }
  20770. // Restore submeshes
  20771. this.releaseSubMeshes();
  20772. this.subMeshes = submeshes;
  20773. return this;
  20774. };
  20775. /**
  20776. * Modifies the mesh geometry according to its own current World Matrix.
  20777. * The mesh World Matrix is then reset.
  20778. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20779. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20780. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20781. * Returns the Mesh.
  20782. */
  20783. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20784. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20785. this.scaling.copyFromFloats(1, 1, 1);
  20786. this.position.copyFromFloats(0, 0, 0);
  20787. this.rotation.copyFromFloats(0, 0, 0);
  20788. //only if quaternion is already set
  20789. if (this.rotationQuaternion) {
  20790. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20791. }
  20792. this._worldMatrix = BABYLON.Matrix.Identity();
  20793. return this;
  20794. };
  20795. Object.defineProperty(Mesh.prototype, "_positions", {
  20796. // Cache
  20797. get: function () {
  20798. if (this._geometry) {
  20799. return this._geometry._positions;
  20800. }
  20801. return null;
  20802. },
  20803. enumerable: true,
  20804. configurable: true
  20805. });
  20806. Mesh.prototype._resetPointsArrayCache = function () {
  20807. if (this._geometry) {
  20808. this._geometry._resetPointsArrayCache();
  20809. }
  20810. return this;
  20811. };
  20812. Mesh.prototype._generatePointsArray = function () {
  20813. if (this._geometry) {
  20814. return this._geometry._generatePointsArray();
  20815. }
  20816. return false;
  20817. };
  20818. /**
  20819. * Returns a new Mesh object generated from the current mesh properties.
  20820. * This method must not get confused with createInstance().
  20821. * The parameter `name` is a string, the name given to the new mesh.
  20822. * The optional parameter `newParent` can be any Node object (default `null`).
  20823. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20824. * 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.
  20825. */
  20826. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20827. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20828. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20829. };
  20830. /**
  20831. * Disposes the mesh.
  20832. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20833. */
  20834. Mesh.prototype.dispose = function (doNotRecurse) {
  20835. var _this = this;
  20836. this.morphTargetManager = undefined;
  20837. if (this._geometry) {
  20838. this._geometry.releaseForMesh(this, true);
  20839. }
  20840. // Sources
  20841. var meshes = this.getScene().meshes;
  20842. meshes.forEach(function (mesh) {
  20843. if (mesh._source && mesh._source === _this) {
  20844. mesh._source = null;
  20845. }
  20846. });
  20847. this._source = null;
  20848. // Instances
  20849. if (this._instancesBuffer) {
  20850. this._instancesBuffer.dispose();
  20851. this._instancesBuffer = null;
  20852. }
  20853. while (this.instances.length) {
  20854. this.instances[0].dispose();
  20855. }
  20856. // Highlight layers.
  20857. var highlightLayers = this.getScene().highlightLayers;
  20858. for (var i = 0; i < highlightLayers.length; i++) {
  20859. var highlightLayer = highlightLayers[i];
  20860. if (highlightLayer) {
  20861. highlightLayer.removeMesh(this);
  20862. highlightLayer.removeExcludedMesh(this);
  20863. }
  20864. }
  20865. _super.prototype.dispose.call(this, doNotRecurse);
  20866. };
  20867. /**
  20868. * Modifies the mesh geometry according to a displacement map.
  20869. * 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.
  20870. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20871. * This method returns nothing.
  20872. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20873. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20874. * 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.
  20875. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20876. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20877. *
  20878. * Returns the Mesh.
  20879. */
  20880. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20881. var _this = this;
  20882. var scene = this.getScene();
  20883. var onload = function (img) {
  20884. // Getting height map data
  20885. var canvas = document.createElement("canvas");
  20886. var context = canvas.getContext("2d");
  20887. var heightMapWidth = img.width;
  20888. var heightMapHeight = img.height;
  20889. canvas.width = heightMapWidth;
  20890. canvas.height = heightMapHeight;
  20891. context.drawImage(img, 0, 0);
  20892. // Create VertexData from map data
  20893. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20894. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20895. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20896. //execute success callback, if set
  20897. if (onSuccess) {
  20898. onSuccess(_this);
  20899. }
  20900. };
  20901. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20902. return this;
  20903. };
  20904. /**
  20905. * Modifies the mesh geometry according to a displacementMap buffer.
  20906. * 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.
  20907. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20908. * This method returns nothing.
  20909. * 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.
  20910. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20911. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20912. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20913. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20914. *
  20915. * Returns the Mesh.
  20916. */
  20917. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20918. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20919. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20920. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20921. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20922. return this;
  20923. }
  20924. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20925. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20926. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20927. var position = BABYLON.Vector3.Zero();
  20928. var normal = BABYLON.Vector3.Zero();
  20929. var uv = BABYLON.Vector2.Zero();
  20930. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20931. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20932. for (var index = 0; index < positions.length; index += 3) {
  20933. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20934. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20935. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20936. // Compute height
  20937. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20938. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20939. var pos = (u + v * heightMapWidth) * 4;
  20940. var r = buffer[pos] / 255.0;
  20941. var g = buffer[pos + 1] / 255.0;
  20942. var b = buffer[pos + 2] / 255.0;
  20943. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20944. normal.normalize();
  20945. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20946. position = position.add(normal);
  20947. position.toArray(positions, index);
  20948. }
  20949. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20950. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20951. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20952. return this;
  20953. };
  20954. /**
  20955. * Modify the mesh to get a flat shading rendering.
  20956. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20957. * This method returns the Mesh.
  20958. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20959. */
  20960. Mesh.prototype.convertToFlatShadedMesh = function () {
  20961. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20962. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20963. var kinds = this.getVerticesDataKinds();
  20964. var vbs = [];
  20965. var data = [];
  20966. var newdata = [];
  20967. var updatableNormals = false;
  20968. var kindIndex;
  20969. var kind;
  20970. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20971. kind = kinds[kindIndex];
  20972. var vertexBuffer = this.getVertexBuffer(kind);
  20973. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20974. updatableNormals = vertexBuffer.isUpdatable();
  20975. kinds.splice(kindIndex, 1);
  20976. kindIndex--;
  20977. continue;
  20978. }
  20979. vbs[kind] = vertexBuffer;
  20980. data[kind] = vbs[kind].getData();
  20981. newdata[kind] = [];
  20982. }
  20983. // Save previous submeshes
  20984. var previousSubmeshes = this.subMeshes.slice(0);
  20985. var indices = this.getIndices();
  20986. var totalIndices = this.getTotalIndices();
  20987. // Generating unique vertices per face
  20988. var index;
  20989. for (index = 0; index < totalIndices; index++) {
  20990. var vertexIndex = indices[index];
  20991. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20992. kind = kinds[kindIndex];
  20993. var stride = vbs[kind].getStrideSize();
  20994. for (var offset = 0; offset < stride; offset++) {
  20995. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20996. }
  20997. }
  20998. }
  20999. // Updating faces & normal
  21000. var normals = [];
  21001. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21002. for (index = 0; index < totalIndices; index += 3) {
  21003. indices[index] = index;
  21004. indices[index + 1] = index + 1;
  21005. indices[index + 2] = index + 2;
  21006. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21007. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21008. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21009. var p1p2 = p1.subtract(p2);
  21010. var p3p2 = p3.subtract(p2);
  21011. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21012. // Store same normals for every vertex
  21013. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21014. normals.push(normal.x);
  21015. normals.push(normal.y);
  21016. normals.push(normal.z);
  21017. }
  21018. }
  21019. this.setIndices(indices);
  21020. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21021. // Updating vertex buffers
  21022. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21023. kind = kinds[kindIndex];
  21024. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21025. }
  21026. // Updating submeshes
  21027. this.releaseSubMeshes();
  21028. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21029. var previousOne = previousSubmeshes[submeshIndex];
  21030. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21031. }
  21032. this.synchronizeInstances();
  21033. return this;
  21034. };
  21035. /**
  21036. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21037. * In other words, more vertices, no more indices and a single bigger VBO.
  21038. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21039. * Returns the Mesh.
  21040. */
  21041. Mesh.prototype.convertToUnIndexedMesh = function () {
  21042. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21043. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21044. var kinds = this.getVerticesDataKinds();
  21045. var vbs = [];
  21046. var data = [];
  21047. var newdata = [];
  21048. var updatableNormals = false;
  21049. var kindIndex;
  21050. var kind;
  21051. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21052. kind = kinds[kindIndex];
  21053. var vertexBuffer = this.getVertexBuffer(kind);
  21054. vbs[kind] = vertexBuffer;
  21055. data[kind] = vbs[kind].getData();
  21056. newdata[kind] = [];
  21057. }
  21058. // Save previous submeshes
  21059. var previousSubmeshes = this.subMeshes.slice(0);
  21060. var indices = this.getIndices();
  21061. var totalIndices = this.getTotalIndices();
  21062. // Generating unique vertices per face
  21063. var index;
  21064. for (index = 0; index < totalIndices; index++) {
  21065. var vertexIndex = indices[index];
  21066. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21067. kind = kinds[kindIndex];
  21068. var stride = vbs[kind].getStrideSize();
  21069. for (var offset = 0; offset < stride; offset++) {
  21070. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21071. }
  21072. }
  21073. }
  21074. // Updating indices
  21075. for (index = 0; index < totalIndices; index += 3) {
  21076. indices[index] = index;
  21077. indices[index + 1] = index + 1;
  21078. indices[index + 2] = index + 2;
  21079. }
  21080. this.setIndices(indices);
  21081. // Updating vertex buffers
  21082. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21083. kind = kinds[kindIndex];
  21084. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21085. }
  21086. // Updating submeshes
  21087. this.releaseSubMeshes();
  21088. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21089. var previousOne = previousSubmeshes[submeshIndex];
  21090. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21091. }
  21092. this._unIndexed = true;
  21093. this.synchronizeInstances();
  21094. return this;
  21095. };
  21096. /**
  21097. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21098. * This method returns the Mesh.
  21099. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21100. */
  21101. Mesh.prototype.flipFaces = function (flipNormals) {
  21102. if (flipNormals === void 0) { flipNormals = false; }
  21103. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21104. var i;
  21105. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21106. for (i = 0; i < vertex_data.normals.length; i++) {
  21107. vertex_data.normals[i] *= -1;
  21108. }
  21109. }
  21110. var temp;
  21111. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21112. // reassign indices
  21113. temp = vertex_data.indices[i + 1];
  21114. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21115. vertex_data.indices[i + 2] = temp;
  21116. }
  21117. vertex_data.applyToMesh(this);
  21118. return this;
  21119. };
  21120. // Instances
  21121. /**
  21122. * Creates a new InstancedMesh object from the mesh model.
  21123. * An instance shares the same properties and the same material than its model.
  21124. * Only these properties of each instance can then be set individually :
  21125. * - position
  21126. * - rotation
  21127. * - rotationQuaternion
  21128. * - setPivotMatrix
  21129. * - scaling
  21130. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21131. * Warning : this method is not supported for Line mesh and LineSystem
  21132. */
  21133. Mesh.prototype.createInstance = function (name) {
  21134. return new BABYLON.InstancedMesh(name, this);
  21135. };
  21136. /**
  21137. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21138. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21139. * This method returns the Mesh.
  21140. */
  21141. Mesh.prototype.synchronizeInstances = function () {
  21142. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21143. var instance = this.instances[instanceIndex];
  21144. instance._syncSubMeshes();
  21145. }
  21146. return this;
  21147. };
  21148. /**
  21149. * Simplify the mesh according to the given array of settings.
  21150. * Function will return immediately and will simplify async. It returns the Mesh.
  21151. * @param settings a collection of simplification settings.
  21152. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21153. * @param type the type of simplification to run.
  21154. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21155. */
  21156. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21157. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21158. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21159. this.getScene().simplificationQueue.addTask({
  21160. settings: settings,
  21161. parallelProcessing: parallelProcessing,
  21162. mesh: this,
  21163. simplificationType: simplificationType,
  21164. successCallback: successCallback
  21165. });
  21166. return this;
  21167. };
  21168. /**
  21169. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21170. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21171. * This should be used together with the simplification to avoid disappearing triangles.
  21172. * Returns the Mesh.
  21173. * @param successCallback an optional success callback to be called after the optimization finished.
  21174. */
  21175. Mesh.prototype.optimizeIndices = function (successCallback) {
  21176. var _this = this;
  21177. var indices = this.getIndices();
  21178. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21179. var vectorPositions = [];
  21180. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21181. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21182. }
  21183. var dupes = [];
  21184. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21185. var realPos = vectorPositions.length - 1 - iteration;
  21186. var testedPosition = vectorPositions[realPos];
  21187. for (var j = 0; j < realPos; ++j) {
  21188. var againstPosition = vectorPositions[j];
  21189. if (testedPosition.equals(againstPosition)) {
  21190. dupes[realPos] = j;
  21191. break;
  21192. }
  21193. }
  21194. }, function () {
  21195. for (var i = 0; i < indices.length; ++i) {
  21196. indices[i] = dupes[indices[i]] || indices[i];
  21197. }
  21198. //indices are now reordered
  21199. var originalSubMeshes = _this.subMeshes.slice(0);
  21200. _this.setIndices(indices);
  21201. _this.subMeshes = originalSubMeshes;
  21202. if (successCallback) {
  21203. successCallback(_this);
  21204. }
  21205. });
  21206. return this;
  21207. };
  21208. Mesh.prototype.serialize = function (serializationObject) {
  21209. serializationObject.name = this.name;
  21210. serializationObject.id = this.id;
  21211. serializationObject.type = this.getClassName();
  21212. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21213. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21214. }
  21215. serializationObject.position = this.position.asArray();
  21216. if (this.rotationQuaternion) {
  21217. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21218. }
  21219. else if (this.rotation) {
  21220. serializationObject.rotation = this.rotation.asArray();
  21221. }
  21222. serializationObject.scaling = this.scaling.asArray();
  21223. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21224. serializationObject.isEnabled = this.isEnabled();
  21225. serializationObject.isVisible = this.isVisible;
  21226. serializationObject.infiniteDistance = this.infiniteDistance;
  21227. serializationObject.pickable = this.isPickable;
  21228. serializationObject.receiveShadows = this.receiveShadows;
  21229. serializationObject.billboardMode = this.billboardMode;
  21230. serializationObject.visibility = this.visibility;
  21231. serializationObject.checkCollisions = this.checkCollisions;
  21232. serializationObject.isBlocker = this.isBlocker;
  21233. // Parent
  21234. if (this.parent) {
  21235. serializationObject.parentId = this.parent.id;
  21236. }
  21237. // Geometry
  21238. var geometry = this._geometry;
  21239. if (geometry) {
  21240. var geometryId = geometry.id;
  21241. serializationObject.geometryId = geometryId;
  21242. // SubMeshes
  21243. serializationObject.subMeshes = [];
  21244. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21245. var subMesh = this.subMeshes[subIndex];
  21246. serializationObject.subMeshes.push({
  21247. materialIndex: subMesh.materialIndex,
  21248. verticesStart: subMesh.verticesStart,
  21249. verticesCount: subMesh.verticesCount,
  21250. indexStart: subMesh.indexStart,
  21251. indexCount: subMesh.indexCount
  21252. });
  21253. }
  21254. }
  21255. // Material
  21256. if (this.material) {
  21257. serializationObject.materialId = this.material.id;
  21258. }
  21259. else {
  21260. this.material = null;
  21261. }
  21262. // Morph targets
  21263. if (this.morphTargetManager) {
  21264. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21265. }
  21266. // Skeleton
  21267. if (this.skeleton) {
  21268. serializationObject.skeletonId = this.skeleton.id;
  21269. }
  21270. // Physics
  21271. //TODO implement correct serialization for physics impostors.
  21272. if (this.getPhysicsImpostor()) {
  21273. var impostor = this.getPhysicsImpostor();
  21274. serializationObject.physicsMass = impostor.getParam("mass");
  21275. serializationObject.physicsFriction = impostor.getParam("friction");
  21276. serializationObject.physicsRestitution = impostor.getParam("mass");
  21277. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21278. }
  21279. // Metadata
  21280. if (this.metadata) {
  21281. serializationObject.metadata = this.metadata;
  21282. }
  21283. // Instances
  21284. serializationObject.instances = [];
  21285. for (var index = 0; index < this.instances.length; index++) {
  21286. var instance = this.instances[index];
  21287. var serializationInstance = {
  21288. name: instance.name,
  21289. position: instance.position.asArray(),
  21290. scaling: instance.scaling.asArray()
  21291. };
  21292. if (instance.rotationQuaternion) {
  21293. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21294. }
  21295. else if (instance.rotation) {
  21296. serializationInstance.rotation = instance.rotation.asArray();
  21297. }
  21298. serializationObject.instances.push(serializationInstance);
  21299. // Animations
  21300. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21301. serializationInstance.ranges = instance.serializeAnimationRanges();
  21302. }
  21303. //
  21304. // Animations
  21305. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21306. serializationObject.ranges = this.serializeAnimationRanges();
  21307. // Layer mask
  21308. serializationObject.layerMask = this.layerMask;
  21309. // Alpha
  21310. serializationObject.alphaIndex = this.alphaIndex;
  21311. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21312. // Overlay
  21313. serializationObject.overlayAlpha = this.overlayAlpha;
  21314. serializationObject.overlayColor = this.overlayColor.asArray();
  21315. serializationObject.renderOverlay = this.renderOverlay;
  21316. // Fog
  21317. serializationObject.applyFog = this.applyFog;
  21318. // Action Manager
  21319. if (this.actionManager) {
  21320. serializationObject.actions = this.actionManager.serialize(this.name);
  21321. }
  21322. };
  21323. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21324. if (!this.geometry) {
  21325. return;
  21326. }
  21327. this._markSubMeshesAsAttributesDirty();
  21328. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21329. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21330. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21331. this.morphTargetManager = undefined;
  21332. return;
  21333. }
  21334. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21335. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21336. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21337. if (morphTarget.hasNormals) {
  21338. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21339. }
  21340. if (morphTarget.hasTangents) {
  21341. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21342. }
  21343. }
  21344. }
  21345. else {
  21346. var index = 0;
  21347. // Positions
  21348. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21349. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21350. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21351. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21352. }
  21353. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21354. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21355. }
  21356. index++;
  21357. }
  21358. }
  21359. };
  21360. // Statics
  21361. /**
  21362. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21363. * The parameter `parsedMesh` is the mesh to be copied.
  21364. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21365. */
  21366. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21367. var mesh;
  21368. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21369. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21370. }
  21371. else {
  21372. mesh = new Mesh(parsedMesh.name, scene);
  21373. }
  21374. mesh.id = parsedMesh.id;
  21375. if (BABYLON.Tags) {
  21376. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21377. }
  21378. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21379. if (parsedMesh.metadata !== undefined) {
  21380. mesh.metadata = parsedMesh.metadata;
  21381. }
  21382. if (parsedMesh.rotationQuaternion) {
  21383. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21384. }
  21385. else if (parsedMesh.rotation) {
  21386. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21387. }
  21388. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21389. if (parsedMesh.localMatrix) {
  21390. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21391. }
  21392. else if (parsedMesh.pivotMatrix) {
  21393. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21394. }
  21395. mesh.setEnabled(parsedMesh.isEnabled);
  21396. mesh.isVisible = parsedMesh.isVisible;
  21397. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21398. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21399. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21400. if (parsedMesh.applyFog !== undefined) {
  21401. mesh.applyFog = parsedMesh.applyFog;
  21402. }
  21403. if (parsedMesh.pickable !== undefined) {
  21404. mesh.isPickable = parsedMesh.pickable;
  21405. }
  21406. if (parsedMesh.alphaIndex !== undefined) {
  21407. mesh.alphaIndex = parsedMesh.alphaIndex;
  21408. }
  21409. mesh.receiveShadows = parsedMesh.receiveShadows;
  21410. mesh.billboardMode = parsedMesh.billboardMode;
  21411. if (parsedMesh.visibility !== undefined) {
  21412. mesh.visibility = parsedMesh.visibility;
  21413. }
  21414. mesh.checkCollisions = parsedMesh.checkCollisions;
  21415. if (parsedMesh.isBlocker !== undefined) {
  21416. mesh.isBlocker = parsedMesh.isBlocker;
  21417. }
  21418. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21419. // freezeWorldMatrix
  21420. if (parsedMesh.freezeWorldMatrix) {
  21421. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21422. }
  21423. // Parent
  21424. if (parsedMesh.parentId) {
  21425. mesh._waitingParentId = parsedMesh.parentId;
  21426. }
  21427. // Actions
  21428. if (parsedMesh.actions !== undefined) {
  21429. mesh._waitingActions = parsedMesh.actions;
  21430. }
  21431. // Overlay
  21432. if (parsedMesh.overlayAlpha !== undefined) {
  21433. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21434. }
  21435. if (parsedMesh.overlayColor !== undefined) {
  21436. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21437. }
  21438. if (parsedMesh.renderOverlay !== undefined) {
  21439. mesh.renderOverlay = parsedMesh.renderOverlay;
  21440. }
  21441. // Geometry
  21442. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21443. if (parsedMesh.delayLoadingFile) {
  21444. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21445. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21446. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21447. if (parsedMesh._binaryInfo) {
  21448. mesh._binaryInfo = parsedMesh._binaryInfo;
  21449. }
  21450. mesh._delayInfo = [];
  21451. if (parsedMesh.hasUVs) {
  21452. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21453. }
  21454. if (parsedMesh.hasUVs2) {
  21455. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21456. }
  21457. if (parsedMesh.hasUVs3) {
  21458. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21459. }
  21460. if (parsedMesh.hasUVs4) {
  21461. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21462. }
  21463. if (parsedMesh.hasUVs5) {
  21464. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21465. }
  21466. if (parsedMesh.hasUVs6) {
  21467. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21468. }
  21469. if (parsedMesh.hasColors) {
  21470. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21471. }
  21472. if (parsedMesh.hasMatricesIndices) {
  21473. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21474. }
  21475. if (parsedMesh.hasMatricesWeights) {
  21476. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21477. }
  21478. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21479. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21480. mesh._checkDelayState();
  21481. }
  21482. }
  21483. else {
  21484. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21485. }
  21486. // Material
  21487. if (parsedMesh.materialId) {
  21488. mesh.setMaterialByID(parsedMesh.materialId);
  21489. }
  21490. else {
  21491. mesh.material = null;
  21492. }
  21493. // Morph targets
  21494. if (parsedMesh.morphTargetManagerId > -1) {
  21495. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21496. }
  21497. // Skeleton
  21498. if (parsedMesh.skeletonId > -1) {
  21499. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21500. if (parsedMesh.numBoneInfluencers) {
  21501. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21502. }
  21503. }
  21504. // Animations
  21505. if (parsedMesh.animations) {
  21506. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21507. var parsedAnimation = parsedMesh.animations[animationIndex];
  21508. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21509. }
  21510. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21511. }
  21512. if (parsedMesh.autoAnimate) {
  21513. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21514. }
  21515. // Layer Mask
  21516. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21517. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21518. }
  21519. else {
  21520. mesh.layerMask = 0x0FFFFFFF;
  21521. }
  21522. // Physics
  21523. if (parsedMesh.physicsImpostor) {
  21524. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21525. mass: parsedMesh.physicsMass,
  21526. friction: parsedMesh.physicsFriction,
  21527. restitution: parsedMesh.physicsRestitution
  21528. }, scene);
  21529. }
  21530. // Instances
  21531. if (parsedMesh.instances) {
  21532. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21533. var parsedInstance = parsedMesh.instances[index];
  21534. var instance = mesh.createInstance(parsedInstance.name);
  21535. if (BABYLON.Tags) {
  21536. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21537. }
  21538. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21539. if (parsedInstance.parentId) {
  21540. instance._waitingParentId = parsedInstance.parentId;
  21541. }
  21542. if (parsedInstance.rotationQuaternion) {
  21543. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21544. }
  21545. else if (parsedInstance.rotation) {
  21546. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21547. }
  21548. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21549. instance.checkCollisions = mesh.checkCollisions;
  21550. if (parsedMesh.animations) {
  21551. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21552. parsedAnimation = parsedMesh.animations[animationIndex];
  21553. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21554. }
  21555. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21556. }
  21557. }
  21558. }
  21559. return mesh;
  21560. };
  21561. /**
  21562. * Creates a ribbon mesh.
  21563. * Please consider using the same method from the MeshBuilder class instead.
  21564. * 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.
  21565. *
  21566. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21567. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21568. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21569. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21570. * 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.
  21571. * 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.
  21572. * 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
  21573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21576. */
  21577. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21578. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21579. pathArray: pathArray,
  21580. closeArray: closeArray,
  21581. closePath: closePath,
  21582. offset: offset,
  21583. updatable: updatable,
  21584. sideOrientation: sideOrientation,
  21585. instance: instance
  21586. }, scene);
  21587. };
  21588. /**
  21589. * Creates a plane polygonal mesh. By default, this is a disc.
  21590. * Please consider using the same method from the MeshBuilder class instead.
  21591. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21592. * 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.
  21593. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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. */
  21597. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21598. var options = {
  21599. radius: radius,
  21600. tessellation: tessellation,
  21601. sideOrientation: sideOrientation,
  21602. updatable: updatable
  21603. };
  21604. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21605. };
  21606. /**
  21607. * Creates a box mesh.
  21608. * Please consider using the same method from the MeshBuilder class instead.
  21609. * The parameter `size` sets the size (float) of each box side (default 1).
  21610. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21611. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21612. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21613. */
  21614. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21615. var options = {
  21616. size: size,
  21617. sideOrientation: sideOrientation,
  21618. updatable: updatable
  21619. };
  21620. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21621. };
  21622. /**
  21623. * Creates a sphere mesh.
  21624. * Please consider using the same method from the MeshBuilder class instead.
  21625. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21626. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21630. */
  21631. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21632. var options = {
  21633. segments: segments,
  21634. diameterX: diameter,
  21635. diameterY: diameter,
  21636. diameterZ: diameter,
  21637. sideOrientation: sideOrientation,
  21638. updatable: updatable
  21639. };
  21640. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21641. };
  21642. /**
  21643. * Creates a cylinder or a cone mesh.
  21644. * Please consider using the same method from the MeshBuilder class instead.
  21645. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21646. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21647. * 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.
  21648. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21649. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21653. */
  21654. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21655. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21656. if (scene !== undefined) {
  21657. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21658. updatable = scene;
  21659. }
  21660. scene = subdivisions;
  21661. subdivisions = 1;
  21662. }
  21663. var options = {
  21664. height: height,
  21665. diameterTop: diameterTop,
  21666. diameterBottom: diameterBottom,
  21667. tessellation: tessellation,
  21668. subdivisions: subdivisions,
  21669. sideOrientation: sideOrientation,
  21670. updatable: updatable
  21671. };
  21672. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21673. };
  21674. // Torus (Code from SharpDX.org)
  21675. /**
  21676. * Creates a torus mesh.
  21677. * Please consider using the same method from the MeshBuilder class instead.
  21678. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21679. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21680. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21681. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21682. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21684. */
  21685. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21686. var options = {
  21687. diameter: diameter,
  21688. thickness: thickness,
  21689. tessellation: tessellation,
  21690. sideOrientation: sideOrientation,
  21691. updatable: updatable
  21692. };
  21693. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21694. };
  21695. /**
  21696. * Creates a torus knot mesh.
  21697. * Please consider using the same method from the MeshBuilder class instead.
  21698. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21699. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21700. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21701. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21703. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21705. */
  21706. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21707. var options = {
  21708. radius: radius,
  21709. tube: tube,
  21710. radialSegments: radialSegments,
  21711. tubularSegments: tubularSegments,
  21712. p: p,
  21713. q: q,
  21714. sideOrientation: sideOrientation,
  21715. updatable: updatable
  21716. };
  21717. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21718. };
  21719. /**
  21720. * Creates a line mesh.
  21721. * Please consider using the same method from the MeshBuilder class instead.
  21722. * 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.
  21723. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21724. * The parameter `points` is an array successive Vector3.
  21725. * 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
  21726. * When updating an instance, remember that only point positions can change, not the number of points.
  21727. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21728. */
  21729. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21730. var options = {
  21731. points: points,
  21732. updatable: updatable,
  21733. instance: instance
  21734. };
  21735. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21736. };
  21737. /**
  21738. * Creates a dashed line mesh.
  21739. * Please consider using the same method from the MeshBuilder class instead.
  21740. * 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.
  21741. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21742. * The parameter `points` is an array successive Vector3.
  21743. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21744. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21745. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21746. * 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
  21747. * When updating an instance, remember that only point positions can change, not the number of points.
  21748. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21749. */
  21750. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21751. var options = {
  21752. points: points,
  21753. dashSize: dashSize,
  21754. gapSize: gapSize,
  21755. dashNb: dashNb,
  21756. updatable: updatable,
  21757. instance: instance
  21758. };
  21759. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21760. };
  21761. /**
  21762. * Creates a polygon mesh.
  21763. * Please consider using the same method from the MeshBuilder class instead.
  21764. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21765. * 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.
  21766. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21768. * Remember you can only change the shape positions, not their number when updating a polygon.
  21769. */
  21770. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21771. var options = {
  21772. shape: shape,
  21773. holes: holes,
  21774. updatable: updatable,
  21775. sideOrientation: sideOrientation
  21776. };
  21777. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21778. };
  21779. /**
  21780. * Creates an extruded polygon mesh, with depth in the Y direction.
  21781. * Please consider using the same method from the MeshBuilder class instead.
  21782. */
  21783. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21784. var options = {
  21785. shape: shape,
  21786. holes: holes,
  21787. depth: depth,
  21788. updatable: updatable,
  21789. sideOrientation: sideOrientation
  21790. };
  21791. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21792. };
  21793. /**
  21794. * Creates an extruded shape mesh.
  21795. * 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.
  21796. * Please consider using the same method from the MeshBuilder class instead.
  21797. *
  21798. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21799. * 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
  21800. * extruded along the Z axis.
  21801. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21802. * 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.
  21803. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21804. * 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
  21805. * 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
  21806. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21810. */
  21811. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21812. var options = {
  21813. shape: shape,
  21814. path: path,
  21815. scale: scale,
  21816. rotation: rotation,
  21817. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21818. sideOrientation: sideOrientation,
  21819. instance: instance,
  21820. updatable: updatable
  21821. };
  21822. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21823. };
  21824. /**
  21825. * Creates an custom extruded shape mesh.
  21826. * 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.
  21827. * Please consider using the same method from the MeshBuilder class instead.
  21828. *
  21829. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21830. * 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
  21831. * extruded along the Z axis.
  21832. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21833. * 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
  21834. * and the distance of this point from the begining of the path :
  21835. * ```javascript
  21836. * var rotationFunction = function(i, distance) {
  21837. * // do things
  21838. * return rotationValue; }
  21839. * ```
  21840. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21841. * 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
  21842. * and the distance of this point from the begining of the path :
  21843. * ```javascript
  21844. * var scaleFunction = function(i, distance) {
  21845. * // do things
  21846. * return scaleValue;}
  21847. * ```
  21848. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21849. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21850. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21851. * 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
  21852. * 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
  21853. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21855. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21857. */
  21858. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21859. var options = {
  21860. shape: shape,
  21861. path: path,
  21862. scaleFunction: scaleFunction,
  21863. rotationFunction: rotationFunction,
  21864. ribbonCloseArray: ribbonCloseArray,
  21865. ribbonClosePath: ribbonClosePath,
  21866. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21867. sideOrientation: sideOrientation,
  21868. instance: instance,
  21869. updatable: updatable
  21870. };
  21871. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21872. };
  21873. /**
  21874. * Creates lathe mesh.
  21875. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21876. * Please consider using the same method from the MeshBuilder class instead.
  21877. * 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
  21878. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21879. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21880. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21884. */
  21885. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21886. var options = {
  21887. shape: shape,
  21888. radius: radius,
  21889. tessellation: tessellation,
  21890. sideOrientation: sideOrientation,
  21891. updatable: updatable
  21892. };
  21893. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21894. };
  21895. /**
  21896. * Creates a plane mesh.
  21897. * Please consider using the same method from the MeshBuilder class instead.
  21898. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21902. */
  21903. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21904. var options = {
  21905. size: size,
  21906. width: size,
  21907. height: size,
  21908. sideOrientation: sideOrientation,
  21909. updatable: updatable
  21910. };
  21911. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21912. };
  21913. /**
  21914. * Creates a ground mesh.
  21915. * Please consider using the same method from the MeshBuilder class instead.
  21916. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21917. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21919. */
  21920. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21921. var options = {
  21922. width: width,
  21923. height: height,
  21924. subdivisions: subdivisions,
  21925. updatable: updatable
  21926. };
  21927. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21928. };
  21929. /**
  21930. * Creates a tiled ground mesh.
  21931. * Please consider using the same method from the MeshBuilder class instead.
  21932. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21933. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21934. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21935. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21936. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21937. * numbers of subdivisions on the ground width and height of each tile.
  21938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21939. */
  21940. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21941. var options = {
  21942. xmin: xmin,
  21943. zmin: zmin,
  21944. xmax: xmax,
  21945. zmax: zmax,
  21946. subdivisions: subdivisions,
  21947. precision: precision,
  21948. updatable: updatable
  21949. };
  21950. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21951. };
  21952. /**
  21953. * Creates a ground mesh from a height map.
  21954. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21955. * Please consider using the same method from the MeshBuilder class instead.
  21956. * The parameter `url` sets the URL of the height map image resource.
  21957. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21958. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21959. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21960. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21961. * 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).
  21962. * This function is passed the newly built mesh :
  21963. * ```javascript
  21964. * function(mesh) { // do things
  21965. * return; }
  21966. * ```
  21967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21968. */
  21969. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21970. var options = {
  21971. width: width,
  21972. height: height,
  21973. subdivisions: subdivisions,
  21974. minHeight: minHeight,
  21975. maxHeight: maxHeight,
  21976. updatable: updatable,
  21977. onReady: onReady
  21978. };
  21979. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21980. };
  21981. /**
  21982. * Creates a tube mesh.
  21983. * 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.
  21984. * Please consider using the same method from the MeshBuilder class instead.
  21985. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21986. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21987. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21988. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21989. * 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.
  21990. * It must return a radius value (positive float) :
  21991. * ```javascript
  21992. * var radiusFunction = function(i, distance) {
  21993. * // do things
  21994. * return radius; }
  21995. * ```
  21996. * 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
  21997. * 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
  21998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21999. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22001. */
  22002. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22003. var options = {
  22004. path: path,
  22005. radius: radius,
  22006. tessellation: tessellation,
  22007. radiusFunction: radiusFunction,
  22008. arc: 1,
  22009. cap: cap,
  22010. updatable: updatable,
  22011. sideOrientation: sideOrientation,
  22012. instance: instance
  22013. };
  22014. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22015. };
  22016. /**
  22017. * Creates a polyhedron mesh.
  22018. * Please consider using the same method from the MeshBuilder class instead.
  22019. * 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
  22020. * to choose the wanted type.
  22021. * The parameter `size` (positive float, default 1) sets the polygon size.
  22022. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22023. * 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`.
  22024. * 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
  22025. * 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)`).
  22026. * 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
  22027. * 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.
  22028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22031. */
  22032. Mesh.CreatePolyhedron = function (name, options, scene) {
  22033. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22034. };
  22035. /**
  22036. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22037. * Please consider using the same method from the MeshBuilder class instead.
  22038. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22039. * 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`).
  22040. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22041. * 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.
  22042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22045. */
  22046. Mesh.CreateIcoSphere = function (name, options, scene) {
  22047. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22048. };
  22049. /**
  22050. * Creates a decal mesh.
  22051. * Please consider using the same method from the MeshBuilder class instead.
  22052. * 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.
  22053. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22054. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22055. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22056. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22057. */
  22058. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22059. var options = {
  22060. position: position,
  22061. normal: normal,
  22062. size: size,
  22063. angle: angle
  22064. };
  22065. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22066. };
  22067. // Skeletons
  22068. /**
  22069. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22070. */
  22071. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22072. var source;
  22073. if (!this._sourcePositions) {
  22074. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22075. this._sourcePositions = new Float32Array(source);
  22076. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22077. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22078. }
  22079. }
  22080. return this._sourcePositions;
  22081. };
  22082. /**
  22083. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22084. */
  22085. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22086. var source;
  22087. if (!this._sourceNormals) {
  22088. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22089. this._sourceNormals = new Float32Array(source);
  22090. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22091. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22092. }
  22093. }
  22094. return this._sourceNormals;
  22095. };
  22096. /**
  22097. * Updates the vertex buffer by applying transformation from the bones.
  22098. * Returns the Mesh.
  22099. *
  22100. * @param {skeleton} skeleton to apply
  22101. */
  22102. Mesh.prototype.applySkeleton = function (skeleton) {
  22103. if (!this.geometry) {
  22104. return this;
  22105. }
  22106. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22107. return this;
  22108. }
  22109. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22110. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22111. return this;
  22112. }
  22113. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22114. return this;
  22115. }
  22116. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22117. return this;
  22118. }
  22119. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22120. return this;
  22121. }
  22122. if (!this._sourcePositions) {
  22123. var submeshes = this.subMeshes.slice();
  22124. this.setPositionsForCPUSkinning();
  22125. this.subMeshes = submeshes;
  22126. }
  22127. if (!this._sourceNormals) {
  22128. this.setNormalsForCPUSkinning();
  22129. }
  22130. // positionsData checks for not being Float32Array will only pass at most once
  22131. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22132. if (!(positionsData instanceof Float32Array)) {
  22133. positionsData = new Float32Array(positionsData);
  22134. }
  22135. // normalsData checks for not being Float32Array will only pass at most once
  22136. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22137. if (!(normalsData instanceof Float32Array)) {
  22138. normalsData = new Float32Array(normalsData);
  22139. }
  22140. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22141. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22142. var needExtras = this.numBoneInfluencers > 4;
  22143. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22144. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22145. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22146. var tempVector3 = BABYLON.Vector3.Zero();
  22147. var finalMatrix = new BABYLON.Matrix();
  22148. var tempMatrix = new BABYLON.Matrix();
  22149. var matWeightIdx = 0;
  22150. var inf;
  22151. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22152. var weight;
  22153. for (inf = 0; inf < 4; inf++) {
  22154. weight = matricesWeightsData[matWeightIdx + inf];
  22155. if (weight > 0) {
  22156. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22157. finalMatrix.addToSelf(tempMatrix);
  22158. }
  22159. else
  22160. break;
  22161. }
  22162. if (needExtras) {
  22163. for (inf = 0; inf < 4; inf++) {
  22164. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22165. if (weight > 0) {
  22166. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22167. finalMatrix.addToSelf(tempMatrix);
  22168. }
  22169. else
  22170. break;
  22171. }
  22172. }
  22173. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22174. tempVector3.toArray(positionsData, index);
  22175. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22176. tempVector3.toArray(normalsData, index);
  22177. finalMatrix.reset();
  22178. }
  22179. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22180. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22181. return this;
  22182. };
  22183. // Tools
  22184. /**
  22185. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22186. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22187. */
  22188. Mesh.MinMax = function (meshes) {
  22189. var minVector = null;
  22190. var maxVector = null;
  22191. meshes.forEach(function (mesh, index, array) {
  22192. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22193. if (!minVector) {
  22194. minVector = boundingBox.minimumWorld;
  22195. maxVector = boundingBox.maximumWorld;
  22196. }
  22197. else {
  22198. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22199. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22200. }
  22201. });
  22202. return {
  22203. min: minVector,
  22204. max: maxVector
  22205. };
  22206. };
  22207. /**
  22208. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22209. */
  22210. Mesh.Center = function (meshesOrMinMaxVector) {
  22211. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22212. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22213. };
  22214. /**
  22215. * Merge the array of meshes into a single mesh for performance reasons.
  22216. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22217. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22218. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22219. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22220. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22221. */
  22222. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22223. if (disposeSource === void 0) { disposeSource = true; }
  22224. var index;
  22225. if (!allow32BitsIndices) {
  22226. var totalVertices = 0;
  22227. // Counting vertices
  22228. for (index = 0; index < meshes.length; index++) {
  22229. if (meshes[index]) {
  22230. totalVertices += meshes[index].getTotalVertices();
  22231. if (totalVertices > 65536) {
  22232. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22233. return null;
  22234. }
  22235. }
  22236. }
  22237. }
  22238. // Merge
  22239. var vertexData;
  22240. var otherVertexData;
  22241. var indiceArray = new Array();
  22242. var source;
  22243. for (index = 0; index < meshes.length; index++) {
  22244. if (meshes[index]) {
  22245. meshes[index].computeWorldMatrix(true);
  22246. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22247. otherVertexData.transform(meshes[index].getWorldMatrix());
  22248. if (vertexData) {
  22249. vertexData.merge(otherVertexData);
  22250. }
  22251. else {
  22252. vertexData = otherVertexData;
  22253. source = meshes[index];
  22254. }
  22255. if (subdivideWithSubMeshes) {
  22256. indiceArray.push(meshes[index].getTotalIndices());
  22257. }
  22258. }
  22259. }
  22260. if (!meshSubclass) {
  22261. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22262. }
  22263. vertexData.applyToMesh(meshSubclass);
  22264. // Setting properties
  22265. meshSubclass.material = source.material;
  22266. meshSubclass.checkCollisions = source.checkCollisions;
  22267. // Cleaning
  22268. if (disposeSource) {
  22269. for (index = 0; index < meshes.length; index++) {
  22270. if (meshes[index]) {
  22271. meshes[index].dispose();
  22272. }
  22273. }
  22274. }
  22275. // Subdivide
  22276. if (subdivideWithSubMeshes) {
  22277. //-- Suppresions du submesh global
  22278. meshSubclass.releaseSubMeshes();
  22279. index = 0;
  22280. var offset = 0;
  22281. //-- aplique la subdivision en fonction du tableau d'indices
  22282. while (index < indiceArray.length) {
  22283. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22284. offset += indiceArray[index];
  22285. index++;
  22286. }
  22287. }
  22288. return meshSubclass;
  22289. };
  22290. return Mesh;
  22291. }(BABYLON.AbstractMesh));
  22292. // Consts
  22293. Mesh._FRONTSIDE = 0;
  22294. Mesh._BACKSIDE = 1;
  22295. Mesh._DOUBLESIDE = 2;
  22296. Mesh._DEFAULTSIDE = 0;
  22297. Mesh._NO_CAP = 0;
  22298. Mesh._CAP_START = 1;
  22299. Mesh._CAP_END = 2;
  22300. Mesh._CAP_ALL = 3;
  22301. BABYLON.Mesh = Mesh;
  22302. })(BABYLON || (BABYLON = {}));
  22303. //# sourceMappingURL=babylon.mesh.js.map
  22304. var BABYLON;
  22305. (function (BABYLON) {
  22306. var BaseSubMesh = (function () {
  22307. function BaseSubMesh() {
  22308. }
  22309. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22310. get: function () {
  22311. return this._materialEffect;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22317. if (this._materialEffect === effect) {
  22318. return;
  22319. }
  22320. this._materialDefines = defines;
  22321. this._materialEffect = effect;
  22322. };
  22323. return BaseSubMesh;
  22324. }());
  22325. BABYLON.BaseSubMesh = BaseSubMesh;
  22326. var SubMesh = (function (_super) {
  22327. __extends(SubMesh, _super);
  22328. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22329. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22330. var _this = _super.call(this) || this;
  22331. _this.materialIndex = materialIndex;
  22332. _this.verticesStart = verticesStart;
  22333. _this.verticesCount = verticesCount;
  22334. _this.indexStart = indexStart;
  22335. _this.indexCount = indexCount;
  22336. _this._renderId = 0;
  22337. _this._mesh = mesh;
  22338. _this._renderingMesh = renderingMesh || mesh;
  22339. mesh.subMeshes.push(_this);
  22340. _this._trianglePlanes = [];
  22341. _this._id = mesh.subMeshes.length - 1;
  22342. if (createBoundingBox) {
  22343. _this.refreshBoundingInfo();
  22344. mesh.computeWorldMatrix(true);
  22345. }
  22346. return _this;
  22347. }
  22348. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22349. get: function () {
  22350. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. /**
  22356. * Returns the submesh BoudingInfo object.
  22357. */
  22358. SubMesh.prototype.getBoundingInfo = function () {
  22359. if (this.IsGlobal) {
  22360. return this._mesh.getBoundingInfo();
  22361. }
  22362. return this._boundingInfo;
  22363. };
  22364. /**
  22365. * Sets the submesh BoundingInfo.
  22366. * Return the SubMesh.
  22367. */
  22368. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22369. this._boundingInfo = boundingInfo;
  22370. return this;
  22371. };
  22372. /**
  22373. * Returns the mesh of the current submesh.
  22374. */
  22375. SubMesh.prototype.getMesh = function () {
  22376. return this._mesh;
  22377. };
  22378. /**
  22379. * Returns the rendering mesh of the submesh.
  22380. */
  22381. SubMesh.prototype.getRenderingMesh = function () {
  22382. return this._renderingMesh;
  22383. };
  22384. /**
  22385. * Returns the submesh material.
  22386. */
  22387. SubMesh.prototype.getMaterial = function () {
  22388. var rootMaterial = this._renderingMesh.material;
  22389. if (rootMaterial && rootMaterial.getSubMaterial) {
  22390. var multiMaterial = rootMaterial;
  22391. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22392. if (this._currentMaterial !== effectiveMaterial) {
  22393. this._currentMaterial = effectiveMaterial;
  22394. if (this._materialDefines) {
  22395. this._materialDefines.markAllAsDirty();
  22396. }
  22397. }
  22398. return effectiveMaterial;
  22399. }
  22400. if (!rootMaterial) {
  22401. return this._mesh.getScene().defaultMaterial;
  22402. }
  22403. return rootMaterial;
  22404. };
  22405. // Methods
  22406. /**
  22407. * Sets a new updated BoundingInfo object to the submesh.
  22408. * Returns the SubMesh.
  22409. */
  22410. SubMesh.prototype.refreshBoundingInfo = function () {
  22411. this._lastColliderWorldVertices = null;
  22412. if (this.IsGlobal) {
  22413. return;
  22414. }
  22415. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22416. if (!data) {
  22417. this._boundingInfo = this._mesh._boundingInfo;
  22418. return;
  22419. }
  22420. var indices = this._renderingMesh.getIndices();
  22421. var extend;
  22422. //is this the only submesh?
  22423. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22424. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22425. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22426. }
  22427. else {
  22428. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22429. }
  22430. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22431. return this;
  22432. };
  22433. SubMesh.prototype._checkCollision = function (collider) {
  22434. return this.getBoundingInfo()._checkCollision(collider);
  22435. };
  22436. /**
  22437. * Updates the submesh BoundingInfo.
  22438. * Returns the Submesh.
  22439. */
  22440. SubMesh.prototype.updateBoundingInfo = function (world) {
  22441. if (!this.getBoundingInfo()) {
  22442. this.refreshBoundingInfo();
  22443. }
  22444. this.getBoundingInfo().update(world);
  22445. return this;
  22446. };
  22447. /**
  22448. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22449. * Boolean returned.
  22450. */
  22451. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22452. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22453. };
  22454. /**
  22455. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22456. * Boolean returned.
  22457. */
  22458. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22459. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22460. };
  22461. /**
  22462. * Renders the submesh.
  22463. * Returns it.
  22464. */
  22465. SubMesh.prototype.render = function (enableAlphaMode) {
  22466. this._renderingMesh.render(this, enableAlphaMode);
  22467. return this;
  22468. };
  22469. /**
  22470. * Returns a new Index Buffer.
  22471. * Type returned : WebGLBuffer.
  22472. */
  22473. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22474. if (!this._linesIndexBuffer) {
  22475. var linesIndices = [];
  22476. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22477. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22478. }
  22479. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22480. this.linesIndexCount = linesIndices.length;
  22481. }
  22482. return this._linesIndexBuffer;
  22483. };
  22484. /**
  22485. * True is the passed Ray intersects the submesh bounding box.
  22486. * Boolean returned.
  22487. */
  22488. SubMesh.prototype.canIntersects = function (ray) {
  22489. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22490. };
  22491. /**
  22492. * Returns an object IntersectionInfo.
  22493. */
  22494. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22495. var intersectInfo = null;
  22496. // LineMesh first as it's also a Mesh...
  22497. if (this._mesh instanceof BABYLON.LinesMesh) {
  22498. var lineMesh = this._mesh;
  22499. // Line test
  22500. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22501. var p0 = positions[indices[index]];
  22502. var p1 = positions[indices[index + 1]];
  22503. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22504. if (length < 0) {
  22505. continue;
  22506. }
  22507. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22508. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22509. if (fastCheck) {
  22510. break;
  22511. }
  22512. }
  22513. }
  22514. }
  22515. else {
  22516. // Triangles test
  22517. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22518. var p0 = positions[indices[index]];
  22519. var p1 = positions[indices[index + 1]];
  22520. var p2 = positions[indices[index + 2]];
  22521. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22522. if (currentIntersectInfo) {
  22523. if (currentIntersectInfo.distance < 0) {
  22524. continue;
  22525. }
  22526. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22527. intersectInfo = currentIntersectInfo;
  22528. intersectInfo.faceId = index / 3;
  22529. if (fastCheck) {
  22530. break;
  22531. }
  22532. }
  22533. }
  22534. }
  22535. }
  22536. return intersectInfo;
  22537. };
  22538. // Clone
  22539. /**
  22540. * Creates a new Submesh from the passed Mesh.
  22541. */
  22542. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22543. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22544. if (!this.IsGlobal) {
  22545. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22546. }
  22547. return result;
  22548. };
  22549. // Dispose
  22550. /**
  22551. * Disposes the Submesh.
  22552. * Returns nothing.
  22553. */
  22554. SubMesh.prototype.dispose = function () {
  22555. if (this._linesIndexBuffer) {
  22556. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22557. this._linesIndexBuffer = null;
  22558. }
  22559. // Remove from mesh
  22560. var index = this._mesh.subMeshes.indexOf(this);
  22561. this._mesh.subMeshes.splice(index, 1);
  22562. };
  22563. // Statics
  22564. /**
  22565. * Creates a new Submesh from the passed parameters :
  22566. * - materialIndex (integer) : the index of the main mesh material.
  22567. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22568. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22569. * - mesh (Mesh) : the main mesh to create the submesh from.
  22570. * - renderingMesh (optional Mesh) : rendering mesh.
  22571. */
  22572. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22573. var minVertexIndex = Number.MAX_VALUE;
  22574. var maxVertexIndex = -Number.MAX_VALUE;
  22575. renderingMesh = renderingMesh || mesh;
  22576. var indices = renderingMesh.getIndices();
  22577. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22578. var vertexIndex = indices[index];
  22579. if (vertexIndex < minVertexIndex)
  22580. minVertexIndex = vertexIndex;
  22581. if (vertexIndex > maxVertexIndex)
  22582. maxVertexIndex = vertexIndex;
  22583. }
  22584. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22585. };
  22586. return SubMesh;
  22587. }(BaseSubMesh));
  22588. BABYLON.SubMesh = SubMesh;
  22589. })(BABYLON || (BABYLON = {}));
  22590. //# sourceMappingURL=babylon.subMesh.js.map
  22591. var BABYLON;
  22592. (function (BABYLON) {
  22593. var EffectFallbacks = (function () {
  22594. function EffectFallbacks() {
  22595. this._defines = {};
  22596. this._currentRank = 32;
  22597. this._maxRank = -1;
  22598. }
  22599. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22600. if (!this._defines[rank]) {
  22601. if (rank < this._currentRank) {
  22602. this._currentRank = rank;
  22603. }
  22604. if (rank > this._maxRank) {
  22605. this._maxRank = rank;
  22606. }
  22607. this._defines[rank] = new Array();
  22608. }
  22609. this._defines[rank].push(define);
  22610. };
  22611. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22612. this._meshRank = rank;
  22613. this._mesh = mesh;
  22614. if (rank < this._currentRank) {
  22615. this._currentRank = rank;
  22616. }
  22617. if (rank > this._maxRank) {
  22618. this._maxRank = rank;
  22619. }
  22620. };
  22621. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22622. get: function () {
  22623. return this._currentRank <= this._maxRank;
  22624. },
  22625. enumerable: true,
  22626. configurable: true
  22627. });
  22628. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22629. // First we try to switch to CPU skinning
  22630. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22631. this._mesh.computeBonesUsingShaders = false;
  22632. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22633. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22634. var scene = this._mesh.getScene();
  22635. for (var index = 0; index < scene.meshes.length; index++) {
  22636. var otherMesh = scene.meshes[index];
  22637. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22638. otherMesh.computeBonesUsingShaders = false;
  22639. }
  22640. }
  22641. }
  22642. else {
  22643. var currentFallbacks = this._defines[this._currentRank];
  22644. if (currentFallbacks) {
  22645. for (var index = 0; index < currentFallbacks.length; index++) {
  22646. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22647. }
  22648. }
  22649. this._currentRank++;
  22650. }
  22651. return currentDefines;
  22652. };
  22653. return EffectFallbacks;
  22654. }());
  22655. BABYLON.EffectFallbacks = EffectFallbacks;
  22656. var EffectCreationOptions = (function () {
  22657. function EffectCreationOptions() {
  22658. }
  22659. return EffectCreationOptions;
  22660. }());
  22661. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22662. var Effect = (function () {
  22663. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22664. var _this = this;
  22665. this.uniqueId = 0;
  22666. this.onCompileObservable = new BABYLON.Observable();
  22667. this.onErrorObservable = new BABYLON.Observable();
  22668. this.onBindObservable = new BABYLON.Observable();
  22669. this._uniformBuffersNames = {};
  22670. this._isReady = false;
  22671. this._compilationError = "";
  22672. this._valueCache = {};
  22673. this.name = baseName;
  22674. if (attributesNamesOrOptions.attributes) {
  22675. var options = attributesNamesOrOptions;
  22676. this._engine = uniformsNamesOrEngine;
  22677. this._attributesNames = options.attributes;
  22678. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22679. this._samplers = options.samplers;
  22680. this.defines = options.defines;
  22681. this.onError = options.onError;
  22682. this.onCompiled = options.onCompiled;
  22683. this._fallbacks = options.fallbacks;
  22684. this._indexParameters = options.indexParameters;
  22685. if (options.uniformBuffersNames) {
  22686. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22687. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22688. }
  22689. }
  22690. }
  22691. else {
  22692. this._engine = engine;
  22693. this.defines = defines;
  22694. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22695. this._samplers = samplers;
  22696. this._attributesNames = attributesNamesOrOptions;
  22697. this.onError = onError;
  22698. this.onCompiled = onCompiled;
  22699. this._indexParameters = indexParameters;
  22700. this._fallbacks = fallbacks;
  22701. }
  22702. this.uniqueId = Effect._uniqueIdSeed++;
  22703. var vertexSource;
  22704. var fragmentSource;
  22705. if (baseName.vertexElement) {
  22706. vertexSource = document.getElementById(baseName.vertexElement);
  22707. if (!vertexSource) {
  22708. vertexSource = baseName.vertexElement;
  22709. }
  22710. }
  22711. else {
  22712. vertexSource = baseName.vertex || baseName;
  22713. }
  22714. if (baseName.fragmentElement) {
  22715. fragmentSource = document.getElementById(baseName.fragmentElement);
  22716. if (!fragmentSource) {
  22717. fragmentSource = baseName.fragmentElement;
  22718. }
  22719. }
  22720. else {
  22721. fragmentSource = baseName.fragment || baseName;
  22722. }
  22723. this._loadVertexShader(vertexSource, function (vertexCode) {
  22724. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22725. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22726. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22727. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22728. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22729. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22730. });
  22731. });
  22732. });
  22733. });
  22734. });
  22735. });
  22736. }
  22737. Object.defineProperty(Effect.prototype, "key", {
  22738. get: function () {
  22739. return this._key;
  22740. },
  22741. enumerable: true,
  22742. configurable: true
  22743. });
  22744. // Properties
  22745. Effect.prototype.isReady = function () {
  22746. return this._isReady;
  22747. };
  22748. Effect.prototype.getEngine = function () {
  22749. return this._engine;
  22750. };
  22751. Effect.prototype.getProgram = function () {
  22752. return this._program;
  22753. };
  22754. Effect.prototype.getAttributesNames = function () {
  22755. return this._attributesNames;
  22756. };
  22757. Effect.prototype.getAttributeLocation = function (index) {
  22758. return this._attributes[index];
  22759. };
  22760. Effect.prototype.getAttributeLocationByName = function (name) {
  22761. var index = this._attributesNames.indexOf(name);
  22762. return this._attributes[index];
  22763. };
  22764. Effect.prototype.getAttributesCount = function () {
  22765. return this._attributes.length;
  22766. };
  22767. Effect.prototype.getUniformIndex = function (uniformName) {
  22768. return this._uniformsNames.indexOf(uniformName);
  22769. };
  22770. Effect.prototype.getUniform = function (uniformName) {
  22771. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22772. };
  22773. Effect.prototype.getSamplers = function () {
  22774. return this._samplers;
  22775. };
  22776. Effect.prototype.getCompilationError = function () {
  22777. return this._compilationError;
  22778. };
  22779. Effect.prototype.getVertexShaderSource = function () {
  22780. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22781. };
  22782. Effect.prototype.getFragmentShaderSource = function () {
  22783. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22784. };
  22785. // Methods
  22786. Effect.prototype.executeWhenCompiled = function (func) {
  22787. var _this = this;
  22788. if (this.isReady()) {
  22789. func(this);
  22790. return;
  22791. }
  22792. var observer = this.onCompileObservable.add(function (effect) {
  22793. _this.onCompileObservable.remove(observer);
  22794. func(effect);
  22795. });
  22796. };
  22797. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22798. // DOM element ?
  22799. if (vertex instanceof HTMLElement) {
  22800. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22801. callback(vertexCode);
  22802. return;
  22803. }
  22804. // Base64 encoded ?
  22805. if (vertex.substr(0, 7) === "base64:") {
  22806. var vertexBinary = window.atob(vertex.substr(7));
  22807. callback(vertexBinary);
  22808. return;
  22809. }
  22810. // Is in local store ?
  22811. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22812. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22813. return;
  22814. }
  22815. var vertexShaderUrl;
  22816. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22817. vertexShaderUrl = vertex;
  22818. }
  22819. else {
  22820. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22821. }
  22822. // Vertex shader
  22823. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22824. };
  22825. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22826. // DOM element ?
  22827. if (fragment instanceof HTMLElement) {
  22828. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22829. callback(fragmentCode);
  22830. return;
  22831. }
  22832. // Base64 encoded ?
  22833. if (fragment.substr(0, 7) === "base64:") {
  22834. var fragmentBinary = window.atob(fragment.substr(7));
  22835. callback(fragmentBinary);
  22836. return;
  22837. }
  22838. // Is in local store ?
  22839. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22840. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22841. return;
  22842. }
  22843. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22844. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22845. return;
  22846. }
  22847. var fragmentShaderUrl;
  22848. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22849. fragmentShaderUrl = fragment;
  22850. }
  22851. else {
  22852. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22853. }
  22854. // Fragment shader
  22855. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22856. };
  22857. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22858. // Rebuild shaders source code
  22859. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22860. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22861. vertexCode = prefix + vertexCode;
  22862. fragmentCode = prefix + fragmentCode;
  22863. // Number lines of shaders source code
  22864. var i = 2;
  22865. var regex = /\n/gm;
  22866. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22867. i = 2;
  22868. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22869. // Dump shaders name and formatted source code
  22870. if (this.name.vertexElement) {
  22871. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22872. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22873. }
  22874. else if (this.name.vertex) {
  22875. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22876. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22877. }
  22878. else {
  22879. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22880. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22881. }
  22882. };
  22883. ;
  22884. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22885. var preparedSourceCode = this._processPrecision(sourceCode);
  22886. if (this._engine.webGLVersion == 1) {
  22887. callback(preparedSourceCode);
  22888. return;
  22889. }
  22890. // Already converted
  22891. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22892. callback(preparedSourceCode.replace("#version 300 es", ""));
  22893. return;
  22894. }
  22895. // Remove extensions
  22896. // #extension GL_OES_standard_derivatives : enable
  22897. // #extension GL_EXT_shader_texture_lod : enable
  22898. // #extension GL_EXT_frag_depth : enable
  22899. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22900. var result = preparedSourceCode.replace(regex, "");
  22901. // Migrate to GLSL v300
  22902. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22903. result = result.replace(/attribute[ \t]/g, "in ");
  22904. result = result.replace(/[ \t]attribute/g, " in");
  22905. if (isFragment) {
  22906. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22907. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22908. result = result.replace(/texture2D\(/g, "texture(");
  22909. result = result.replace(/textureCube\(/g, "texture(");
  22910. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22911. result = result.replace(/gl_FragColor/g, "glFragColor");
  22912. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22913. }
  22914. callback(result);
  22915. };
  22916. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22917. var _this = this;
  22918. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22919. var match = regex.exec(sourceCode);
  22920. var returnValue = new String(sourceCode);
  22921. while (match != null) {
  22922. var includeFile = match[1];
  22923. // Uniform declaration
  22924. if (includeFile.indexOf("__decl__") !== -1) {
  22925. includeFile = includeFile.replace(/__decl__/, "");
  22926. if (this._engine.webGLVersion != 1) {
  22927. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22928. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22929. }
  22930. includeFile = includeFile + "Declaration";
  22931. }
  22932. if (Effect.IncludesShadersStore[includeFile]) {
  22933. // Substitution
  22934. var includeContent = Effect.IncludesShadersStore[includeFile];
  22935. if (match[2]) {
  22936. var splits = match[3].split(",");
  22937. for (var index = 0; index < splits.length; index += 2) {
  22938. var source = new RegExp(splits[index], "g");
  22939. var dest = splits[index + 1];
  22940. includeContent = includeContent.replace(source, dest);
  22941. }
  22942. }
  22943. if (match[4]) {
  22944. var indexString = match[5];
  22945. if (indexString.indexOf("..") !== -1) {
  22946. var indexSplits = indexString.split("..");
  22947. var minIndex = parseInt(indexSplits[0]);
  22948. var maxIndex = parseInt(indexSplits[1]);
  22949. var sourceIncludeContent = includeContent.slice(0);
  22950. includeContent = "";
  22951. if (isNaN(maxIndex)) {
  22952. maxIndex = this._indexParameters[indexSplits[1]];
  22953. }
  22954. for (var i = minIndex; i < maxIndex; i++) {
  22955. if (this._engine.webGLVersion === 1) {
  22956. // Ubo replacement
  22957. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22958. return p1 + "{X}";
  22959. });
  22960. }
  22961. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22962. }
  22963. }
  22964. else {
  22965. if (this._engine.webGLVersion === 1) {
  22966. // Ubo replacement
  22967. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22968. return p1 + "{X}";
  22969. });
  22970. }
  22971. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22972. }
  22973. }
  22974. // Replace
  22975. returnValue = returnValue.replace(match[0], includeContent);
  22976. }
  22977. else {
  22978. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22979. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22980. Effect.IncludesShadersStore[includeFile] = fileContent;
  22981. _this._processIncludes(returnValue, callback);
  22982. });
  22983. return;
  22984. }
  22985. match = regex.exec(sourceCode);
  22986. }
  22987. callback(returnValue);
  22988. };
  22989. Effect.prototype._processPrecision = function (source) {
  22990. if (source.indexOf("precision highp float") === -1) {
  22991. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22992. source = "precision mediump float;\n" + source;
  22993. }
  22994. else {
  22995. source = "precision highp float;\n" + source;
  22996. }
  22997. }
  22998. else {
  22999. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23000. source = source.replace("precision highp float", "precision mediump float");
  23001. }
  23002. }
  23003. return source;
  23004. };
  23005. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23006. try {
  23007. var engine = this._engine;
  23008. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23009. if (engine.webGLVersion > 1) {
  23010. for (var name in this._uniformBuffersNames) {
  23011. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23012. }
  23013. }
  23014. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23015. this._attributes = engine.getAttributes(this._program, attributesNames);
  23016. var index;
  23017. for (index = 0; index < this._samplers.length; index++) {
  23018. var sampler = this.getUniform(this._samplers[index]);
  23019. if (sampler == null) {
  23020. this._samplers.splice(index, 1);
  23021. index--;
  23022. }
  23023. }
  23024. engine.bindSamplers(this);
  23025. this._compilationError = "";
  23026. this._isReady = true;
  23027. if (this.onCompiled) {
  23028. this.onCompiled(this);
  23029. }
  23030. this.onCompileObservable.notifyObservers(this);
  23031. }
  23032. catch (e) {
  23033. this._compilationError = e.message;
  23034. // Let's go through fallbacks then
  23035. BABYLON.Tools.Error("Unable to compile effect:");
  23036. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23037. return " " + uniform;
  23038. }));
  23039. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23040. return " " + attribute;
  23041. }));
  23042. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23043. BABYLON.Tools.Error("Error: " + this._compilationError);
  23044. if (fallbacks && fallbacks.isMoreFallbacks) {
  23045. BABYLON.Tools.Error("Trying next fallback.");
  23046. defines = fallbacks.reduce(defines);
  23047. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23048. }
  23049. else {
  23050. if (this.onError) {
  23051. this.onError(this, this._compilationError);
  23052. }
  23053. this.onErrorObservable.notifyObservers(this);
  23054. }
  23055. }
  23056. };
  23057. Object.defineProperty(Effect.prototype, "isSupported", {
  23058. get: function () {
  23059. return this._compilationError === "";
  23060. },
  23061. enumerable: true,
  23062. configurable: true
  23063. });
  23064. Effect.prototype._bindTexture = function (channel, texture) {
  23065. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23066. };
  23067. Effect.prototype.setTexture = function (channel, texture) {
  23068. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23069. };
  23070. Effect.prototype.setTextureArray = function (channel, textures) {
  23071. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23072. var initialPos = this._samplers.indexOf(channel);
  23073. for (var index = 1; index < textures.length; index++) {
  23074. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23075. }
  23076. }
  23077. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23078. };
  23079. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23080. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23081. };
  23082. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23083. var cache = this._valueCache[uniformName];
  23084. var flag = matrix.updateFlag;
  23085. if (cache !== undefined && cache === flag) {
  23086. return false;
  23087. }
  23088. this._valueCache[uniformName] = flag;
  23089. return true;
  23090. };
  23091. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23092. var cache = this._valueCache[uniformName];
  23093. if (!cache) {
  23094. cache = [x, y];
  23095. this._valueCache[uniformName] = cache;
  23096. return true;
  23097. }
  23098. var changed = false;
  23099. if (cache[0] !== x) {
  23100. cache[0] = x;
  23101. changed = true;
  23102. }
  23103. if (cache[1] !== y) {
  23104. cache[1] = y;
  23105. changed = true;
  23106. }
  23107. return changed;
  23108. };
  23109. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23110. var cache = this._valueCache[uniformName];
  23111. if (!cache) {
  23112. cache = [x, y, z];
  23113. this._valueCache[uniformName] = cache;
  23114. return true;
  23115. }
  23116. var changed = false;
  23117. if (cache[0] !== x) {
  23118. cache[0] = x;
  23119. changed = true;
  23120. }
  23121. if (cache[1] !== y) {
  23122. cache[1] = y;
  23123. changed = true;
  23124. }
  23125. if (cache[2] !== z) {
  23126. cache[2] = z;
  23127. changed = true;
  23128. }
  23129. return changed;
  23130. };
  23131. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23132. var cache = this._valueCache[uniformName];
  23133. if (!cache) {
  23134. cache = [x, y, z, w];
  23135. this._valueCache[uniformName] = cache;
  23136. return true;
  23137. }
  23138. var changed = false;
  23139. if (cache[0] !== x) {
  23140. cache[0] = x;
  23141. changed = true;
  23142. }
  23143. if (cache[1] !== y) {
  23144. cache[1] = y;
  23145. changed = true;
  23146. }
  23147. if (cache[2] !== z) {
  23148. cache[2] = z;
  23149. changed = true;
  23150. }
  23151. if (cache[3] !== w) {
  23152. cache[3] = w;
  23153. changed = true;
  23154. }
  23155. return changed;
  23156. };
  23157. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23158. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23159. return;
  23160. }
  23161. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23162. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23163. };
  23164. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23165. this._engine.bindUniformBlock(this._program, blockName, index);
  23166. };
  23167. Effect.prototype.setIntArray = function (uniformName, array) {
  23168. this._valueCache[uniformName] = null;
  23169. this._engine.setIntArray(this.getUniform(uniformName), array);
  23170. return this;
  23171. };
  23172. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23173. this._valueCache[uniformName] = null;
  23174. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23175. return this;
  23176. };
  23177. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23178. this._valueCache[uniformName] = null;
  23179. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23180. return this;
  23181. };
  23182. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23183. this._valueCache[uniformName] = null;
  23184. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23185. return this;
  23186. };
  23187. Effect.prototype.setFloatArray = function (uniformName, array) {
  23188. this._valueCache[uniformName] = null;
  23189. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23190. return this;
  23191. };
  23192. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23193. this._valueCache[uniformName] = null;
  23194. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23195. return this;
  23196. };
  23197. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23198. this._valueCache[uniformName] = null;
  23199. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23200. return this;
  23201. };
  23202. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23203. this._valueCache[uniformName] = null;
  23204. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23205. return this;
  23206. };
  23207. Effect.prototype.setArray = function (uniformName, array) {
  23208. this._valueCache[uniformName] = null;
  23209. this._engine.setArray(this.getUniform(uniformName), array);
  23210. return this;
  23211. };
  23212. Effect.prototype.setArray2 = function (uniformName, array) {
  23213. this._valueCache[uniformName] = null;
  23214. this._engine.setArray2(this.getUniform(uniformName), array);
  23215. return this;
  23216. };
  23217. Effect.prototype.setArray3 = function (uniformName, array) {
  23218. this._valueCache[uniformName] = null;
  23219. this._engine.setArray3(this.getUniform(uniformName), array);
  23220. return this;
  23221. };
  23222. Effect.prototype.setArray4 = function (uniformName, array) {
  23223. this._valueCache[uniformName] = null;
  23224. this._engine.setArray4(this.getUniform(uniformName), array);
  23225. return this;
  23226. };
  23227. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23228. if (!matrices) {
  23229. return;
  23230. }
  23231. this._valueCache[uniformName] = null;
  23232. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23233. return this;
  23234. };
  23235. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23236. if (this._cacheMatrix(uniformName, matrix)) {
  23237. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23238. }
  23239. return this;
  23240. };
  23241. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23242. this._valueCache[uniformName] = null;
  23243. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23244. return this;
  23245. };
  23246. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23247. this._valueCache[uniformName] = null;
  23248. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23249. return this;
  23250. };
  23251. Effect.prototype.setFloat = function (uniformName, value) {
  23252. var cache = this._valueCache[uniformName];
  23253. if (cache !== undefined && cache === value)
  23254. return this;
  23255. this._valueCache[uniformName] = value;
  23256. this._engine.setFloat(this.getUniform(uniformName), value);
  23257. return this;
  23258. };
  23259. Effect.prototype.setBool = function (uniformName, bool) {
  23260. var cache = this._valueCache[uniformName];
  23261. if (cache !== undefined && cache === bool)
  23262. return this;
  23263. this._valueCache[uniformName] = bool;
  23264. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23265. return this;
  23266. };
  23267. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23268. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23269. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23270. }
  23271. return this;
  23272. };
  23273. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23274. if (this._cacheFloat2(uniformName, x, y)) {
  23275. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23276. }
  23277. return this;
  23278. };
  23279. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23280. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23281. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23282. }
  23283. return this;
  23284. };
  23285. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23286. if (this._cacheFloat3(uniformName, x, y, z)) {
  23287. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23288. }
  23289. return this;
  23290. };
  23291. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23292. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23293. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23294. }
  23295. return this;
  23296. };
  23297. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23298. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23299. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23300. }
  23301. return this;
  23302. };
  23303. Effect.prototype.setColor3 = function (uniformName, color3) {
  23304. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23305. this._engine.setColor3(this.getUniform(uniformName), color3);
  23306. }
  23307. return this;
  23308. };
  23309. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23310. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23311. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23312. }
  23313. return this;
  23314. };
  23315. Effect.prototype._recombineShader = function (node) {
  23316. if (node.define) {
  23317. if (node.condition) {
  23318. var defineIndex = this.defines.indexOf("#define " + node.define);
  23319. if (defineIndex === -1) {
  23320. return null;
  23321. }
  23322. var nextComma = this.defines.indexOf("\n", defineIndex);
  23323. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23324. var condition = defineValue + node.condition;
  23325. if (!eval(condition)) {
  23326. return null;
  23327. }
  23328. }
  23329. else if (node.ndef) {
  23330. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23331. return null;
  23332. }
  23333. }
  23334. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23335. return null;
  23336. }
  23337. }
  23338. var result = "";
  23339. for (var index = 0; index < node.children.length; index++) {
  23340. var line = node.children[index];
  23341. if (line.children) {
  23342. var combined = this._recombineShader(line);
  23343. if (combined !== null) {
  23344. result += combined + "\r\n";
  23345. }
  23346. continue;
  23347. }
  23348. if (line.length > 0) {
  23349. result += line + "\r\n";
  23350. }
  23351. }
  23352. return result;
  23353. };
  23354. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23355. var root = {
  23356. children: []
  23357. };
  23358. var currentNode = root;
  23359. var lines = shaderString.split("\n");
  23360. for (var index = 0; index < lines.length; index++) {
  23361. var line = lines[index].trim();
  23362. // #ifdef
  23363. var pos = line.indexOf("#ifdef ");
  23364. if (pos !== -1) {
  23365. var define = line.substr(pos + 7);
  23366. var newNode = {
  23367. condition: null,
  23368. ndef: false,
  23369. define: define,
  23370. children: [],
  23371. parent: currentNode
  23372. };
  23373. currentNode.children.push(newNode);
  23374. currentNode = newNode;
  23375. continue;
  23376. }
  23377. // #ifndef
  23378. var pos = line.indexOf("#ifndef ");
  23379. if (pos !== -1) {
  23380. var define = line.substr(pos + 8);
  23381. newNode = {
  23382. condition: null,
  23383. define: define,
  23384. ndef: true,
  23385. children: [],
  23386. parent: currentNode
  23387. };
  23388. currentNode.children.push(newNode);
  23389. currentNode = newNode;
  23390. continue;
  23391. }
  23392. // #if
  23393. var pos = line.indexOf("#if ");
  23394. if (pos !== -1) {
  23395. var define = line.substr(pos + 4).trim();
  23396. var conditionPos = define.indexOf(" ");
  23397. newNode = {
  23398. condition: define.substr(conditionPos + 1),
  23399. define: define.substr(0, conditionPos),
  23400. ndef: false,
  23401. children: [],
  23402. parent: currentNode
  23403. };
  23404. currentNode.children.push(newNode);
  23405. currentNode = newNode;
  23406. continue;
  23407. }
  23408. // #endif
  23409. pos = line.indexOf("#endif");
  23410. if (pos !== -1) {
  23411. currentNode = currentNode.parent;
  23412. continue;
  23413. }
  23414. currentNode.children.push(line);
  23415. }
  23416. // Recombine
  23417. return this._recombineShader(root);
  23418. };
  23419. return Effect;
  23420. }());
  23421. Effect._uniqueIdSeed = 0;
  23422. Effect._baseCache = {};
  23423. // Statics
  23424. Effect.ShadersStore = {};
  23425. Effect.IncludesShadersStore = {};
  23426. BABYLON.Effect = Effect;
  23427. })(BABYLON || (BABYLON = {}));
  23428. //# sourceMappingURL=babylon.effect.js.map
  23429. var BABYLON;
  23430. (function (BABYLON) {
  23431. var MaterialHelper = (function () {
  23432. function MaterialHelper() {
  23433. }
  23434. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23435. if (defines._areMiscDirty) {
  23436. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23437. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23438. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23439. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23440. }
  23441. };
  23442. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23443. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23444. var changed = false;
  23445. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23446. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23447. changed = true;
  23448. }
  23449. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23450. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23451. changed = true;
  23452. }
  23453. if (defines["INSTANCES"] !== useInstances) {
  23454. defines["INSTANCES"] = useInstances;
  23455. changed = true;
  23456. }
  23457. if (changed) {
  23458. defines.markAsUnprocessed();
  23459. }
  23460. };
  23461. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23462. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23463. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23464. return false;
  23465. }
  23466. defines._normals = defines._needNormals;
  23467. defines._uvs = defines._needUVs;
  23468. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23469. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23470. defines["TANGENT"] = true;
  23471. }
  23472. if (defines._needUVs) {
  23473. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23474. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23475. }
  23476. else {
  23477. defines["UV1"] = false;
  23478. defines["UV2"] = false;
  23479. }
  23480. if (useVertexColor) {
  23481. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23482. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23483. }
  23484. if (useBones) {
  23485. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23486. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23487. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23488. }
  23489. else {
  23490. defines["NUM_BONE_INFLUENCERS"] = 0;
  23491. defines["BonesPerMesh"] = 0;
  23492. }
  23493. }
  23494. if (useMorphTargets) {
  23495. if (mesh.morphTargetManager) {
  23496. var manager = mesh.morphTargetManager;
  23497. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23498. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23499. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23500. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23501. }
  23502. else {
  23503. defines["MORPHTARGETS_TANGENT"] = false;
  23504. defines["MORPHTARGETS_NORMAL"] = false;
  23505. defines["MORPHTARGETS"] = false;
  23506. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23507. }
  23508. }
  23509. return true;
  23510. };
  23511. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23512. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23513. if (disableLighting === void 0) { disableLighting = false; }
  23514. if (!defines._areLightsDirty) {
  23515. return defines._needNormals;
  23516. }
  23517. var lightIndex = 0;
  23518. var needNormals = false;
  23519. var needRebuild = false;
  23520. var lightmapMode = false;
  23521. var shadowEnabled = false;
  23522. var specularEnabled = false;
  23523. if (scene.lightsEnabled && !disableLighting) {
  23524. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23525. var light = _a[_i];
  23526. needNormals = true;
  23527. if (defines["LIGHT" + lightIndex] === undefined) {
  23528. needRebuild = true;
  23529. }
  23530. defines["LIGHT" + lightIndex] = true;
  23531. defines["SPOTLIGHT" + lightIndex] = false;
  23532. defines["HEMILIGHT" + lightIndex] = false;
  23533. defines["POINTLIGHT" + lightIndex] = false;
  23534. defines["DIRLIGHT" + lightIndex] = false;
  23535. var type;
  23536. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23537. type = "SPOTLIGHT" + lightIndex;
  23538. }
  23539. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23540. type = "HEMILIGHT" + lightIndex;
  23541. }
  23542. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23543. type = "POINTLIGHT" + lightIndex;
  23544. }
  23545. else {
  23546. type = "DIRLIGHT" + lightIndex;
  23547. }
  23548. defines[type] = true;
  23549. // Specular
  23550. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23551. specularEnabled = true;
  23552. }
  23553. // Shadows
  23554. defines["SHADOW" + lightIndex] = false;
  23555. defines["SHADOWPCF" + lightIndex] = false;
  23556. defines["SHADOWESM" + lightIndex] = false;
  23557. defines["SHADOWCUBE" + lightIndex] = false;
  23558. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23559. var shadowGenerator = light.getShadowGenerator();
  23560. if (shadowGenerator) {
  23561. shadowEnabled = true;
  23562. shadowGenerator.prepareDefines(defines, lightIndex);
  23563. }
  23564. }
  23565. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23566. lightmapMode = true;
  23567. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23568. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23569. }
  23570. else {
  23571. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23572. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23573. }
  23574. lightIndex++;
  23575. if (lightIndex === maxSimultaneousLights)
  23576. break;
  23577. }
  23578. }
  23579. defines["SPECULARTERM"] = specularEnabled;
  23580. defines["SHADOWS"] = shadowEnabled;
  23581. // Resetting all other lights if any
  23582. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23583. if (defines["LIGHT" + index] !== undefined) {
  23584. defines["LIGHT" + index] = false;
  23585. defines["HEMILIGHT" + lightIndex] = false;
  23586. defines["POINTLIGHT" + lightIndex] = false;
  23587. defines["DIRLIGHT" + lightIndex] = false;
  23588. defines["SPOTLIGHT" + lightIndex] = false;
  23589. defines["SHADOW" + lightIndex] = false;
  23590. }
  23591. }
  23592. var caps = scene.getEngine().getCaps();
  23593. if (defines["SHADOWFLOAT"] === undefined) {
  23594. needRebuild = true;
  23595. }
  23596. defines["SHADOWFLOAT"] = shadowEnabled &&
  23597. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23598. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23599. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23600. if (needRebuild) {
  23601. defines.rebuild();
  23602. }
  23603. return needNormals;
  23604. };
  23605. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23606. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23607. var uniformsList, uniformBuffersList, samplersList, defines;
  23608. if (uniformsListOrOptions.uniformsNames) {
  23609. var options = uniformsListOrOptions;
  23610. uniformsList = options.uniformsNames;
  23611. uniformBuffersList = options.uniformBuffersNames;
  23612. samplersList = options.samplers;
  23613. defines = options.defines;
  23614. maxSimultaneousLights = options.maxSimultaneousLights;
  23615. }
  23616. else {
  23617. uniformsList = uniformsListOrOptions;
  23618. }
  23619. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23620. if (!defines["LIGHT" + lightIndex]) {
  23621. break;
  23622. }
  23623. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23624. if (uniformBuffersList) {
  23625. uniformBuffersList.push("Light" + lightIndex);
  23626. }
  23627. samplersList.push("shadowSampler" + lightIndex);
  23628. }
  23629. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23630. uniformsList.push("morphTargetInfluences");
  23631. }
  23632. };
  23633. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23634. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23635. if (!defines["SHADOWS"]) {
  23636. return;
  23637. }
  23638. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23639. if (!defines["LIGHT" + lightIndex]) {
  23640. break;
  23641. }
  23642. if (lightIndex > 0) {
  23643. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23644. }
  23645. if (defines["SHADOW" + lightIndex]) {
  23646. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23647. }
  23648. if (defines["SHADOWPCF" + lightIndex]) {
  23649. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23650. }
  23651. if (defines["SHADOWESM" + lightIndex]) {
  23652. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23653. }
  23654. }
  23655. };
  23656. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23657. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23658. if (influencers > 0) {
  23659. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23660. var manager = mesh.morphTargetManager;
  23661. var normal = manager.supportsNormals && defines["NORMAL"];
  23662. var tangent = manager.supportsTangents && defines["TANGENT"];
  23663. for (var index = 0; index < influencers; index++) {
  23664. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23665. if (normal) {
  23666. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23667. }
  23668. if (tangent) {
  23669. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23670. }
  23671. if (attribs.length > maxAttributesCount) {
  23672. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23673. }
  23674. }
  23675. }
  23676. };
  23677. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23678. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23679. fallbacks.addCPUSkinningFallback(0, mesh);
  23680. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23681. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23682. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23683. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23684. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23685. }
  23686. }
  23687. };
  23688. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23689. if (defines["INSTANCES"]) {
  23690. attribs.push("world0");
  23691. attribs.push("world1");
  23692. attribs.push("world2");
  23693. attribs.push("world3");
  23694. }
  23695. };
  23696. // Bindings
  23697. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23698. if (light.shadowEnabled && mesh.receiveShadows) {
  23699. var shadowGenerator = light.getShadowGenerator();
  23700. if (shadowGenerator) {
  23701. shadowGenerator.bindShadowLight(lightIndex, effect);
  23702. }
  23703. }
  23704. };
  23705. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23706. light.transferToEffect(effect, lightIndex + "");
  23707. };
  23708. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  23709. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23710. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  23711. var lightIndex = 0;
  23712. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23713. var light = _a[_i];
  23714. var scaledIntensity = light.getScaledIntensity();
  23715. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23716. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23717. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  23718. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  23719. if (defines["SPECULARTERM"]) {
  23720. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  23721. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23722. }
  23723. // Shadows
  23724. if (scene.shadowsEnabled) {
  23725. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23726. }
  23727. light._uniformBuffer.update();
  23728. lightIndex++;
  23729. if (lightIndex === maxSimultaneousLights)
  23730. break;
  23731. }
  23732. };
  23733. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23734. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23735. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23736. effect.setColor3("vFogColor", scene.fogColor);
  23737. }
  23738. };
  23739. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23740. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23741. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23742. if (matrices) {
  23743. effect.setMatrices("mBones", matrices);
  23744. }
  23745. }
  23746. };
  23747. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23748. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23749. return;
  23750. }
  23751. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23752. };
  23753. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23754. if (defines["LOGARITHMICDEPTH"]) {
  23755. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23756. }
  23757. };
  23758. MaterialHelper.BindClipPlane = function (effect, scene) {
  23759. if (scene.clipPlane) {
  23760. var clipPlane = scene.clipPlane;
  23761. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23762. }
  23763. };
  23764. return MaterialHelper;
  23765. }());
  23766. BABYLON.MaterialHelper = MaterialHelper;
  23767. })(BABYLON || (BABYLON = {}));
  23768. //# sourceMappingURL=babylon.materialHelper.js.map
  23769. var BABYLON;
  23770. (function (BABYLON) {
  23771. var MaterialDefines = (function () {
  23772. function MaterialDefines() {
  23773. this._isDirty = true;
  23774. this._areLightsDirty = true;
  23775. this._areAttributesDirty = true;
  23776. this._areTexturesDirty = true;
  23777. this._areFresnelDirty = true;
  23778. this._areMiscDirty = true;
  23779. this._areImageProcessingDirty = true;
  23780. this._normals = false;
  23781. this._uvs = false;
  23782. this._needNormals = false;
  23783. this._needUVs = false;
  23784. }
  23785. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23786. get: function () {
  23787. return this._isDirty;
  23788. },
  23789. enumerable: true,
  23790. configurable: true
  23791. });
  23792. MaterialDefines.prototype.markAsProcessed = function () {
  23793. this._isDirty = false;
  23794. this._areAttributesDirty = false;
  23795. this._areTexturesDirty = false;
  23796. this._areFresnelDirty = false;
  23797. this._areLightsDirty = false;
  23798. this._areMiscDirty = false;
  23799. this._areImageProcessingDirty = false;
  23800. };
  23801. MaterialDefines.prototype.markAsUnprocessed = function () {
  23802. this._isDirty = true;
  23803. };
  23804. MaterialDefines.prototype.markAllAsDirty = function () {
  23805. this._areTexturesDirty = true;
  23806. this._areAttributesDirty = true;
  23807. this._areLightsDirty = true;
  23808. this._areFresnelDirty = true;
  23809. this._areMiscDirty = true;
  23810. this._areImageProcessingDirty = true;
  23811. this._isDirty = true;
  23812. };
  23813. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  23814. this._areImageProcessingDirty = true;
  23815. this._isDirty = true;
  23816. };
  23817. MaterialDefines.prototype.markAsLightDirty = function () {
  23818. this._areLightsDirty = true;
  23819. this._isDirty = true;
  23820. };
  23821. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23822. this._areAttributesDirty = true;
  23823. this._isDirty = true;
  23824. };
  23825. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23826. this._areTexturesDirty = true;
  23827. this._isDirty = true;
  23828. };
  23829. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23830. this._areFresnelDirty = true;
  23831. this._isDirty = true;
  23832. };
  23833. MaterialDefines.prototype.markAsMiscDirty = function () {
  23834. this._areMiscDirty = true;
  23835. this._isDirty = true;
  23836. };
  23837. MaterialDefines.prototype.rebuild = function () {
  23838. if (this._keys) {
  23839. delete this._keys;
  23840. }
  23841. this._keys = [];
  23842. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23843. var key = _a[_i];
  23844. if (key[0] === "_") {
  23845. continue;
  23846. }
  23847. this._keys.push(key);
  23848. }
  23849. };
  23850. MaterialDefines.prototype.isEqual = function (other) {
  23851. if (this._keys.length !== other._keys.length) {
  23852. return false;
  23853. }
  23854. for (var index = 0; index < this._keys.length; index++) {
  23855. var prop = this._keys[index];
  23856. if (this[prop] !== other[prop]) {
  23857. return false;
  23858. }
  23859. }
  23860. return true;
  23861. };
  23862. MaterialDefines.prototype.cloneTo = function (other) {
  23863. if (this._keys.length !== other._keys.length) {
  23864. other._keys = this._keys.slice(0);
  23865. }
  23866. for (var index = 0; index < this._keys.length; index++) {
  23867. var prop = this._keys[index];
  23868. other[prop] = this[prop];
  23869. }
  23870. };
  23871. MaterialDefines.prototype.reset = function () {
  23872. for (var index = 0; index < this._keys.length; index++) {
  23873. var prop = this._keys[index];
  23874. if (typeof (this[prop]) === "number") {
  23875. this[prop] = 0;
  23876. }
  23877. else {
  23878. this[prop] = false;
  23879. }
  23880. }
  23881. };
  23882. MaterialDefines.prototype.toString = function () {
  23883. var result = "";
  23884. for (var index = 0; index < this._keys.length; index++) {
  23885. var prop = this._keys[index];
  23886. var value = this[prop];
  23887. if (typeof (value) === "number") {
  23888. result += "#define " + prop + " " + this[prop] + "\n";
  23889. }
  23890. else if (value) {
  23891. result += "#define " + prop + "\n";
  23892. }
  23893. }
  23894. return result;
  23895. };
  23896. return MaterialDefines;
  23897. }());
  23898. BABYLON.MaterialDefines = MaterialDefines;
  23899. var Material = (function () {
  23900. function Material(name, scene, doNotAdd) {
  23901. this.checkReadyOnEveryCall = false;
  23902. this.checkReadyOnlyOnce = false;
  23903. this.state = "";
  23904. this.alpha = 1.0;
  23905. this._backFaceCulling = true;
  23906. this.doNotSerialize = false;
  23907. this.storeEffectOnSubMeshes = false;
  23908. /**
  23909. * An event triggered when the material is disposed.
  23910. * @type {BABYLON.Observable}
  23911. */
  23912. this.onDisposeObservable = new BABYLON.Observable();
  23913. /**
  23914. * An event triggered when the material is bound.
  23915. * @type {BABYLON.Observable}
  23916. */
  23917. this.onBindObservable = new BABYLON.Observable();
  23918. /**
  23919. * An event triggered when the material is unbound.
  23920. * @type {BABYLON.Observable}
  23921. */
  23922. this.onUnBindObservable = new BABYLON.Observable();
  23923. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23924. this.disableDepthWrite = false;
  23925. this._fogEnabled = true;
  23926. this.pointSize = 1.0;
  23927. this.zOffset = 0;
  23928. this._wasPreviouslyReady = false;
  23929. this._fillMode = Material.TriangleFillMode;
  23930. this.name = name;
  23931. this.id = name;
  23932. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23933. if (this._scene.useRightHandedSystem) {
  23934. this.sideOrientation = Material.ClockWiseSideOrientation;
  23935. }
  23936. else {
  23937. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23938. }
  23939. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23940. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23941. if (!doNotAdd) {
  23942. this._scene.materials.push(this);
  23943. }
  23944. }
  23945. Object.defineProperty(Material, "TriangleFillMode", {
  23946. get: function () {
  23947. return Material._TriangleFillMode;
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. Object.defineProperty(Material, "WireFrameFillMode", {
  23953. get: function () {
  23954. return Material._WireFrameFillMode;
  23955. },
  23956. enumerable: true,
  23957. configurable: true
  23958. });
  23959. Object.defineProperty(Material, "PointFillMode", {
  23960. get: function () {
  23961. return Material._PointFillMode;
  23962. },
  23963. enumerable: true,
  23964. configurable: true
  23965. });
  23966. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23967. get: function () {
  23968. return Material._ClockWiseSideOrientation;
  23969. },
  23970. enumerable: true,
  23971. configurable: true
  23972. });
  23973. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23974. get: function () {
  23975. return Material._CounterClockWiseSideOrientation;
  23976. },
  23977. enumerable: true,
  23978. configurable: true
  23979. });
  23980. Object.defineProperty(Material, "TextureDirtyFlag", {
  23981. get: function () {
  23982. return Material._TextureDirtyFlag;
  23983. },
  23984. enumerable: true,
  23985. configurable: true
  23986. });
  23987. Object.defineProperty(Material, "LightDirtyFlag", {
  23988. get: function () {
  23989. return Material._LightDirtyFlag;
  23990. },
  23991. enumerable: true,
  23992. configurable: true
  23993. });
  23994. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23995. get: function () {
  23996. return Material._FresnelDirtyFlag;
  23997. },
  23998. enumerable: true,
  23999. configurable: true
  24000. });
  24001. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24002. get: function () {
  24003. return Material._AttributesDirtyFlag;
  24004. },
  24005. enumerable: true,
  24006. configurable: true
  24007. });
  24008. Object.defineProperty(Material, "MiscDirtyFlag", {
  24009. get: function () {
  24010. return Material._MiscDirtyFlag;
  24011. },
  24012. enumerable: true,
  24013. configurable: true
  24014. });
  24015. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24016. get: function () {
  24017. return this._backFaceCulling;
  24018. },
  24019. set: function (value) {
  24020. if (this._backFaceCulling === value) {
  24021. return;
  24022. }
  24023. this._backFaceCulling = value;
  24024. this.markAsDirty(Material.TextureDirtyFlag);
  24025. },
  24026. enumerable: true,
  24027. configurable: true
  24028. });
  24029. Object.defineProperty(Material.prototype, "onDispose", {
  24030. set: function (callback) {
  24031. if (this._onDisposeObserver) {
  24032. this.onDisposeObservable.remove(this._onDisposeObserver);
  24033. }
  24034. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24035. },
  24036. enumerable: true,
  24037. configurable: true
  24038. });
  24039. Object.defineProperty(Material.prototype, "onBind", {
  24040. set: function (callback) {
  24041. if (this._onBindObserver) {
  24042. this.onBindObservable.remove(this._onBindObserver);
  24043. }
  24044. this._onBindObserver = this.onBindObservable.add(callback);
  24045. },
  24046. enumerable: true,
  24047. configurable: true
  24048. });
  24049. Object.defineProperty(Material.prototype, "fogEnabled", {
  24050. get: function () {
  24051. return this._fogEnabled;
  24052. },
  24053. set: function (value) {
  24054. if (this._fogEnabled === value) {
  24055. return;
  24056. }
  24057. this._fogEnabled = value;
  24058. this.markAsDirty(Material.MiscDirtyFlag);
  24059. },
  24060. enumerable: true,
  24061. configurable: true
  24062. });
  24063. Object.defineProperty(Material.prototype, "wireframe", {
  24064. get: function () {
  24065. return this._fillMode === Material.WireFrameFillMode;
  24066. },
  24067. set: function (value) {
  24068. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24069. },
  24070. enumerable: true,
  24071. configurable: true
  24072. });
  24073. Object.defineProperty(Material.prototype, "pointsCloud", {
  24074. get: function () {
  24075. return this._fillMode === Material.PointFillMode;
  24076. },
  24077. set: function (value) {
  24078. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24079. },
  24080. enumerable: true,
  24081. configurable: true
  24082. });
  24083. Object.defineProperty(Material.prototype, "fillMode", {
  24084. get: function () {
  24085. return this._fillMode;
  24086. },
  24087. set: function (value) {
  24088. if (this._fillMode === value) {
  24089. return;
  24090. }
  24091. this._fillMode = value;
  24092. this.markAsDirty(Material.MiscDirtyFlag);
  24093. },
  24094. enumerable: true,
  24095. configurable: true
  24096. });
  24097. /**
  24098. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24099. * subclasses should override adding information pertainent to themselves
  24100. */
  24101. Material.prototype.toString = function (fullDetails) {
  24102. var ret = "Name: " + this.name;
  24103. if (fullDetails) {
  24104. }
  24105. return ret;
  24106. };
  24107. /**
  24108. * Child classes can use it to update shaders
  24109. */
  24110. Material.prototype.getClassName = function () {
  24111. return "Material";
  24112. };
  24113. Object.defineProperty(Material.prototype, "isFrozen", {
  24114. get: function () {
  24115. return this.checkReadyOnlyOnce;
  24116. },
  24117. enumerable: true,
  24118. configurable: true
  24119. });
  24120. Material.prototype.freeze = function () {
  24121. this.checkReadyOnlyOnce = true;
  24122. };
  24123. Material.prototype.unfreeze = function () {
  24124. this.checkReadyOnlyOnce = false;
  24125. };
  24126. Material.prototype.isReady = function (mesh, useInstances) {
  24127. return true;
  24128. };
  24129. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24130. return false;
  24131. };
  24132. Material.prototype.getEffect = function () {
  24133. return this._effect;
  24134. };
  24135. Material.prototype.getScene = function () {
  24136. return this._scene;
  24137. };
  24138. Material.prototype.needAlphaBlending = function () {
  24139. return (this.alpha < 1.0);
  24140. };
  24141. Material.prototype.needAlphaTesting = function () {
  24142. return false;
  24143. };
  24144. Material.prototype.getAlphaTestTexture = function () {
  24145. return null;
  24146. };
  24147. Material.prototype.markDirty = function () {
  24148. this._wasPreviouslyReady = false;
  24149. };
  24150. Material.prototype._preBind = function (effect) {
  24151. var engine = this._scene.getEngine();
  24152. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24153. engine.enableEffect(effect ? effect : this._effect);
  24154. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24155. };
  24156. Material.prototype.bind = function (world, mesh) {
  24157. };
  24158. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24159. };
  24160. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24161. };
  24162. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24163. sceneUbo.bindToEffect(effect, "Scene");
  24164. };
  24165. Material.prototype.bindView = function (effect) {
  24166. if (!this._useUBO) {
  24167. effect.setMatrix("view", this.getScene().getViewMatrix());
  24168. }
  24169. else {
  24170. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24171. }
  24172. };
  24173. Material.prototype.bindViewProjection = function (effect) {
  24174. if (!this._useUBO) {
  24175. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24176. }
  24177. else {
  24178. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24179. }
  24180. };
  24181. Material.prototype._afterBind = function (mesh) {
  24182. this._scene._cachedMaterial = this;
  24183. this.onBindObservable.notifyObservers(mesh);
  24184. if (this.disableDepthWrite) {
  24185. var engine = this._scene.getEngine();
  24186. this._cachedDepthWriteState = engine.getDepthWrite();
  24187. engine.setDepthWrite(false);
  24188. }
  24189. };
  24190. Material.prototype.unbind = function () {
  24191. this.onUnBindObservable.notifyObservers(this);
  24192. if (this.disableDepthWrite) {
  24193. var engine = this._scene.getEngine();
  24194. engine.setDepthWrite(this._cachedDepthWriteState);
  24195. }
  24196. };
  24197. Material.prototype.getActiveTextures = function () {
  24198. return [];
  24199. };
  24200. Material.prototype.clone = function (name) {
  24201. return null;
  24202. };
  24203. Material.prototype.getBindedMeshes = function () {
  24204. var result = new Array();
  24205. for (var index = 0; index < this._scene.meshes.length; index++) {
  24206. var mesh = this._scene.meshes[index];
  24207. if (mesh.material === this) {
  24208. result.push(mesh);
  24209. }
  24210. }
  24211. return result;
  24212. };
  24213. // Force shader compilation including textures ready check
  24214. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24215. var _this = this;
  24216. var subMesh = new BABYLON.BaseSubMesh();
  24217. var scene = this.getScene();
  24218. var engine = scene.getEngine();
  24219. var beforeRenderCallback = function () {
  24220. if (subMesh._materialDefines) {
  24221. subMesh._materialDefines._renderId = -1;
  24222. }
  24223. var alphaTestState = engine.getAlphaTesting();
  24224. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24225. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24226. scene.unregisterBeforeRender(beforeRenderCallback);
  24227. if (onCompiled) {
  24228. onCompiled(_this);
  24229. }
  24230. }
  24231. engine.setAlphaTesting(alphaTestState);
  24232. };
  24233. scene.registerBeforeRender(beforeRenderCallback);
  24234. };
  24235. Material.prototype.markAsDirty = function (flag) {
  24236. if (flag & Material.TextureDirtyFlag) {
  24237. this._markAllSubMeshesAsTexturesDirty();
  24238. }
  24239. if (flag & Material.LightDirtyFlag) {
  24240. this._markAllSubMeshesAsLightsDirty();
  24241. }
  24242. if (flag & Material.FresnelDirtyFlag) {
  24243. this._markAllSubMeshesAsFresnelDirty();
  24244. }
  24245. if (flag & Material.AttributesDirtyFlag) {
  24246. this._markAllSubMeshesAsAttributesDirty();
  24247. }
  24248. if (flag & Material.MiscDirtyFlag) {
  24249. this._markAllSubMeshesAsMiscDirty();
  24250. }
  24251. this.getScene().resetCachedMaterial();
  24252. };
  24253. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24254. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24255. var mesh = _a[_i];
  24256. if (!mesh.subMeshes) {
  24257. continue;
  24258. }
  24259. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24260. var subMesh = _c[_b];
  24261. if (subMesh.getMaterial() !== this) {
  24262. continue;
  24263. }
  24264. if (!subMesh._materialDefines) {
  24265. return;
  24266. }
  24267. func(subMesh._materialDefines);
  24268. }
  24269. }
  24270. };
  24271. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24272. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24273. };
  24274. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24275. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24276. };
  24277. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24278. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24279. };
  24280. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24281. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24282. };
  24283. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24284. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24285. };
  24286. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24287. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24288. };
  24289. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24290. // Animations
  24291. this.getScene().stopAnimation(this);
  24292. // Remove from scene
  24293. var index = this._scene.materials.indexOf(this);
  24294. if (index >= 0) {
  24295. this._scene.materials.splice(index, 1);
  24296. }
  24297. // Remove from meshes
  24298. for (index = 0; index < this._scene.meshes.length; index++) {
  24299. var mesh = this._scene.meshes[index];
  24300. if (mesh.material === this) {
  24301. mesh.material = null;
  24302. if (mesh.geometry) {
  24303. var geometry = mesh.geometry;
  24304. if (this.storeEffectOnSubMeshes) {
  24305. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24306. var subMesh = _a[_i];
  24307. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24308. }
  24309. }
  24310. else {
  24311. geometry._releaseVertexArrayObject(this._effect);
  24312. }
  24313. }
  24314. }
  24315. }
  24316. this._uniformBuffer.dispose();
  24317. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24318. if (forceDisposeEffect && this._effect) {
  24319. if (this.storeEffectOnSubMeshes) {
  24320. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24321. var subMesh = _c[_b];
  24322. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24323. }
  24324. }
  24325. else {
  24326. this._scene.getEngine()._releaseEffect(this._effect);
  24327. }
  24328. this._effect = null;
  24329. }
  24330. // Callback
  24331. this.onDisposeObservable.notifyObservers(this);
  24332. this.onDisposeObservable.clear();
  24333. this.onBindObservable.clear();
  24334. this.onUnBindObservable.clear();
  24335. };
  24336. Material.prototype.serialize = function () {
  24337. return BABYLON.SerializationHelper.Serialize(this);
  24338. };
  24339. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24340. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24341. multiMaterial.id = parsedMultiMaterial.id;
  24342. if (BABYLON.Tags) {
  24343. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24344. }
  24345. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24346. var subMatId = parsedMultiMaterial.materials[matIndex];
  24347. if (subMatId) {
  24348. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24349. }
  24350. else {
  24351. multiMaterial.subMaterials.push(null);
  24352. }
  24353. }
  24354. return multiMaterial;
  24355. };
  24356. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24357. if (!parsedMaterial.customType) {
  24358. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24359. }
  24360. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24361. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24362. if (!BABYLON.LegacyPBRMaterial) {
  24363. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24364. return;
  24365. }
  24366. }
  24367. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24368. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24369. ;
  24370. };
  24371. return Material;
  24372. }());
  24373. Material._TriangleFillMode = 0;
  24374. Material._WireFrameFillMode = 1;
  24375. Material._PointFillMode = 2;
  24376. Material._ClockWiseSideOrientation = 0;
  24377. Material._CounterClockWiseSideOrientation = 1;
  24378. Material._TextureDirtyFlag = 1;
  24379. Material._LightDirtyFlag = 2;
  24380. Material._FresnelDirtyFlag = 4;
  24381. Material._AttributesDirtyFlag = 8;
  24382. Material._MiscDirtyFlag = 16;
  24383. __decorate([
  24384. BABYLON.serialize()
  24385. ], Material.prototype, "id", void 0);
  24386. __decorate([
  24387. BABYLON.serialize()
  24388. ], Material.prototype, "name", void 0);
  24389. __decorate([
  24390. BABYLON.serialize()
  24391. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24392. __decorate([
  24393. BABYLON.serialize()
  24394. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24395. __decorate([
  24396. BABYLON.serialize()
  24397. ], Material.prototype, "state", void 0);
  24398. __decorate([
  24399. BABYLON.serialize()
  24400. ], Material.prototype, "alpha", void 0);
  24401. __decorate([
  24402. BABYLON.serialize("backFaceCulling")
  24403. ], Material.prototype, "_backFaceCulling", void 0);
  24404. __decorate([
  24405. BABYLON.serialize()
  24406. ], Material.prototype, "sideOrientation", void 0);
  24407. __decorate([
  24408. BABYLON.serialize()
  24409. ], Material.prototype, "alphaMode", void 0);
  24410. __decorate([
  24411. BABYLON.serialize()
  24412. ], Material.prototype, "disableDepthWrite", void 0);
  24413. __decorate([
  24414. BABYLON.serialize("fogEnabled")
  24415. ], Material.prototype, "_fogEnabled", void 0);
  24416. __decorate([
  24417. BABYLON.serialize()
  24418. ], Material.prototype, "pointSize", void 0);
  24419. __decorate([
  24420. BABYLON.serialize()
  24421. ], Material.prototype, "zOffset", void 0);
  24422. __decorate([
  24423. BABYLON.serialize()
  24424. ], Material.prototype, "wireframe", null);
  24425. __decorate([
  24426. BABYLON.serialize()
  24427. ], Material.prototype, "pointsCloud", null);
  24428. __decorate([
  24429. BABYLON.serialize()
  24430. ], Material.prototype, "fillMode", null);
  24431. BABYLON.Material = Material;
  24432. })(BABYLON || (BABYLON = {}));
  24433. //# sourceMappingURL=babylon.material.js.map
  24434. var BABYLON;
  24435. (function (BABYLON) {
  24436. var UniformBuffer = (function () {
  24437. /**
  24438. * Uniform buffer objects.
  24439. *
  24440. * Handles blocks of uniform on the GPU.
  24441. *
  24442. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24443. *
  24444. * For more information, please refer to :
  24445. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24446. */
  24447. function UniformBuffer(engine, data, dynamic) {
  24448. this._engine = engine;
  24449. this._noUBO = engine.webGLVersion === 1;
  24450. this._dynamic = dynamic;
  24451. this._data = data || [];
  24452. this._uniformLocations = {};
  24453. this._uniformSizes = {};
  24454. this._uniformLocationPointer = 0;
  24455. this._needSync = false;
  24456. if (this._noUBO) {
  24457. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24458. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24459. this.updateFloat = this._updateFloatForEffect;
  24460. this.updateFloat2 = this._updateFloat2ForEffect;
  24461. this.updateFloat3 = this._updateFloat3ForEffect;
  24462. this.updateFloat4 = this._updateFloat4ForEffect;
  24463. this.updateMatrix = this._updateMatrixForEffect;
  24464. this.updateVector3 = this._updateVector3ForEffect;
  24465. this.updateVector4 = this._updateVector4ForEffect;
  24466. this.updateColor3 = this._updateColor3ForEffect;
  24467. this.updateColor4 = this._updateColor4ForEffect;
  24468. }
  24469. else {
  24470. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24471. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24472. this.updateFloat = this._updateFloatForUniform;
  24473. this.updateFloat2 = this._updateFloat2ForUniform;
  24474. this.updateFloat3 = this._updateFloat3ForUniform;
  24475. this.updateFloat4 = this._updateFloat4ForUniform;
  24476. this.updateMatrix = this._updateMatrixForUniform;
  24477. this.updateVector3 = this._updateVector3ForUniform;
  24478. this.updateVector4 = this._updateVector4ForUniform;
  24479. this.updateColor3 = this._updateColor3ForUniform;
  24480. this.updateColor4 = this._updateColor4ForUniform;
  24481. }
  24482. }
  24483. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24484. // Properties
  24485. /**
  24486. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24487. * or just falling back on setUniformXXX calls.
  24488. */
  24489. get: function () {
  24490. return !this._noUBO;
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24496. /**
  24497. * Indicates if the WebGL underlying uniform buffer is in sync
  24498. * with the javascript cache data.
  24499. */
  24500. get: function () {
  24501. return !this._needSync;
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. /**
  24507. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24508. * Also, a dynamic UniformBuffer will disable cache verification and always
  24509. * update the underlying WebGL uniform buffer to the GPU.
  24510. */
  24511. UniformBuffer.prototype.isDynamic = function () {
  24512. return this._dynamic;
  24513. };
  24514. /**
  24515. * The data cache on JS side.
  24516. */
  24517. UniformBuffer.prototype.getData = function () {
  24518. return this._bufferData;
  24519. };
  24520. /**
  24521. * The underlying WebGL Uniform buffer.
  24522. */
  24523. UniformBuffer.prototype.getBuffer = function () {
  24524. return this._buffer;
  24525. };
  24526. /**
  24527. * std140 layout specifies how to align data within an UBO structure.
  24528. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24529. * for specs.
  24530. */
  24531. UniformBuffer.prototype._fillAlignment = function (size) {
  24532. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24533. // and 4x4 matrices
  24534. // TODO : change if other types are used
  24535. var alignment;
  24536. if (size <= 2) {
  24537. alignment = size;
  24538. }
  24539. else {
  24540. alignment = 4;
  24541. }
  24542. if ((this._uniformLocationPointer % alignment) !== 0) {
  24543. var oldPointer = this._uniformLocationPointer;
  24544. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24545. var diff = this._uniformLocationPointer - oldPointer;
  24546. for (var i = 0; i < diff; i++) {
  24547. this._data.push(0);
  24548. }
  24549. }
  24550. };
  24551. /**
  24552. * Adds an uniform in the buffer.
  24553. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24554. * for the layout to be correct !
  24555. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24556. * @param {number|number[]} size Data size, or data directly.
  24557. */
  24558. UniformBuffer.prototype.addUniform = function (name, size) {
  24559. if (this._noUBO) {
  24560. return;
  24561. }
  24562. if (this._uniformLocations[name] !== undefined) {
  24563. // Already existing uniform
  24564. return;
  24565. }
  24566. // This function must be called in the order of the shader layout !
  24567. // size can be the size of the uniform, or data directly
  24568. var data;
  24569. if (size instanceof Array) {
  24570. data = size;
  24571. size = data.length;
  24572. }
  24573. else {
  24574. size = size;
  24575. data = [];
  24576. // Fill with zeros
  24577. for (var i = 0; i < size; i++) {
  24578. data.push(0);
  24579. }
  24580. }
  24581. this._fillAlignment(size);
  24582. this._uniformSizes[name] = size;
  24583. this._uniformLocations[name] = this._uniformLocationPointer;
  24584. this._uniformLocationPointer += size;
  24585. for (var i = 0; i < size; i++) {
  24586. this._data.push(data[i]);
  24587. }
  24588. this._needSync = true;
  24589. };
  24590. /**
  24591. * Wrapper for addUniform.
  24592. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24593. * @param {Matrix} mat A 4x4 matrix.
  24594. */
  24595. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24596. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24597. };
  24598. /**
  24599. * Wrapper for addUniform.
  24600. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24601. * @param {number} x
  24602. * @param {number} y
  24603. */
  24604. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24605. var temp = [x, y];
  24606. this.addUniform(name, temp);
  24607. };
  24608. /**
  24609. * Wrapper for addUniform.
  24610. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24611. * @param {number} x
  24612. * @param {number} y
  24613. * @param {number} z
  24614. */
  24615. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24616. var temp = [x, y, z];
  24617. this.addUniform(name, temp);
  24618. };
  24619. /**
  24620. * Wrapper for addUniform.
  24621. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24622. * @param {Color3} color
  24623. */
  24624. UniformBuffer.prototype.addColor3 = function (name, color) {
  24625. var temp = [];
  24626. color.toArray(temp);
  24627. this.addUniform(name, temp);
  24628. };
  24629. /**
  24630. * Wrapper for addUniform.
  24631. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24632. * @param {Color3} color
  24633. * @param {number} alpha
  24634. */
  24635. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24636. var temp = [];
  24637. color.toArray(temp);
  24638. temp.push(alpha);
  24639. this.addUniform(name, temp);
  24640. };
  24641. /**
  24642. * Wrapper for addUniform.
  24643. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24644. * @param {Vector3} vector
  24645. */
  24646. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24647. var temp = [];
  24648. vector.toArray(temp);
  24649. this.addUniform(name, temp);
  24650. };
  24651. /**
  24652. * Wrapper for addUniform.
  24653. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24654. */
  24655. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24656. this.addUniform(name, 12);
  24657. };
  24658. /**
  24659. * Wrapper for addUniform.
  24660. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24661. */
  24662. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24663. this.addUniform(name, 8);
  24664. };
  24665. /**
  24666. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24667. */
  24668. UniformBuffer.prototype.create = function () {
  24669. if (this._noUBO) {
  24670. return;
  24671. }
  24672. if (this._buffer) {
  24673. return; // nothing to do
  24674. }
  24675. // See spec, alignment must be filled as a vec4
  24676. this._fillAlignment(4);
  24677. this._bufferData = new Float32Array(this._data);
  24678. if (this._dynamic) {
  24679. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24680. }
  24681. else {
  24682. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24683. }
  24684. this._needSync = true;
  24685. };
  24686. /**
  24687. * Updates the WebGL Uniform Buffer on the GPU.
  24688. * If the `dynamic` flag is set to true, no cache comparison is done.
  24689. * Otherwise, the buffer will be updated only if the cache differs.
  24690. */
  24691. UniformBuffer.prototype.update = function () {
  24692. if (!this._buffer) {
  24693. this.create();
  24694. return;
  24695. }
  24696. if (!this._dynamic && !this._needSync) {
  24697. return;
  24698. }
  24699. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24700. this._needSync = false;
  24701. };
  24702. /**
  24703. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24704. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24705. * @param {number[]|Float32Array} data Flattened data
  24706. * @param {number} size Size of the data.
  24707. */
  24708. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24709. var location = this._uniformLocations[uniformName];
  24710. if (location === undefined) {
  24711. if (this._buffer) {
  24712. // Cannot add an uniform if the buffer is already created
  24713. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24714. return;
  24715. }
  24716. this.addUniform(uniformName, size);
  24717. location = this._uniformLocations[uniformName];
  24718. }
  24719. if (!this._buffer) {
  24720. this.create();
  24721. }
  24722. if (!this._dynamic) {
  24723. // Cache for static uniform buffers
  24724. var changed = false;
  24725. for (var i = 0; i < size; i++) {
  24726. if (this._bufferData[location + i] !== data[i]) {
  24727. changed = true;
  24728. this._bufferData[location + i] = data[i];
  24729. }
  24730. }
  24731. this._needSync = this._needSync || changed;
  24732. }
  24733. else {
  24734. // No cache for dynamic
  24735. for (var i = 0; i < size; i++) {
  24736. this._bufferData[location + i] = data[i];
  24737. }
  24738. }
  24739. };
  24740. // Update methods
  24741. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24742. // To match std140, matrix must be realigned
  24743. for (var i = 0; i < 3; i++) {
  24744. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24745. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24746. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24747. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24748. }
  24749. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24750. };
  24751. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24752. this._currentEffect.setMatrix3x3(name, matrix);
  24753. };
  24754. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24755. this._currentEffect.setMatrix2x2(name, matrix);
  24756. };
  24757. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24758. // To match std140, matrix must be realigned
  24759. for (var i = 0; i < 2; i++) {
  24760. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24761. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24762. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24763. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24764. }
  24765. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24766. };
  24767. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24768. this._currentEffect.setFloat(name, x);
  24769. };
  24770. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24771. UniformBuffer._tempBuffer[0] = x;
  24772. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24773. };
  24774. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24775. if (suffix === void 0) { suffix = ""; }
  24776. this._currentEffect.setFloat2(name + suffix, x, y);
  24777. };
  24778. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24779. if (suffix === void 0) { suffix = ""; }
  24780. UniformBuffer._tempBuffer[0] = x;
  24781. UniformBuffer._tempBuffer[1] = y;
  24782. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24783. };
  24784. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24785. if (suffix === void 0) { suffix = ""; }
  24786. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24787. };
  24788. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24789. if (suffix === void 0) { suffix = ""; }
  24790. UniformBuffer._tempBuffer[0] = x;
  24791. UniformBuffer._tempBuffer[1] = y;
  24792. UniformBuffer._tempBuffer[2] = z;
  24793. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24794. };
  24795. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24796. if (suffix === void 0) { suffix = ""; }
  24797. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24798. };
  24799. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24800. if (suffix === void 0) { suffix = ""; }
  24801. UniformBuffer._tempBuffer[0] = x;
  24802. UniformBuffer._tempBuffer[1] = y;
  24803. UniformBuffer._tempBuffer[2] = z;
  24804. UniformBuffer._tempBuffer[3] = w;
  24805. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24806. };
  24807. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24808. this._currentEffect.setMatrix(name, mat);
  24809. };
  24810. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24811. this.updateUniform(name, mat.toArray(), 16);
  24812. };
  24813. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24814. this._currentEffect.setVector3(name, vector);
  24815. };
  24816. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24817. vector.toArray(UniformBuffer._tempBuffer);
  24818. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24819. };
  24820. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24821. this._currentEffect.setVector4(name, vector);
  24822. };
  24823. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24824. vector.toArray(UniformBuffer._tempBuffer);
  24825. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24826. };
  24827. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24828. if (suffix === void 0) { suffix = ""; }
  24829. this._currentEffect.setColor3(name + suffix, color);
  24830. };
  24831. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24832. if (suffix === void 0) { suffix = ""; }
  24833. color.toArray(UniformBuffer._tempBuffer);
  24834. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24835. };
  24836. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24837. if (suffix === void 0) { suffix = ""; }
  24838. this._currentEffect.setColor4(name + suffix, color, alpha);
  24839. };
  24840. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24841. if (suffix === void 0) { suffix = ""; }
  24842. color.toArray(UniformBuffer._tempBuffer);
  24843. UniformBuffer._tempBuffer[3] = alpha;
  24844. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24845. };
  24846. /**
  24847. * Sets a sampler uniform on the effect.
  24848. * @param {string} name Name of the sampler.
  24849. * @param {Texture} texture
  24850. */
  24851. UniformBuffer.prototype.setTexture = function (name, texture) {
  24852. this._currentEffect.setTexture(name, texture);
  24853. };
  24854. /**
  24855. * Directly updates the value of the uniform in the cache AND on the GPU.
  24856. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24857. * @param {number[]|Float32Array} data Flattened data
  24858. */
  24859. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24860. this.updateUniform(uniformName, data, data.length);
  24861. this.update();
  24862. };
  24863. /**
  24864. * Binds this uniform buffer to an effect.
  24865. * @param {Effect} effect
  24866. * @param {string} name Name of the uniform block in the shader.
  24867. */
  24868. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24869. this._currentEffect = effect;
  24870. if (this._noUBO) {
  24871. return;
  24872. }
  24873. effect.bindUniformBuffer(this._buffer, name);
  24874. };
  24875. /**
  24876. * Disposes the uniform buffer.
  24877. */
  24878. UniformBuffer.prototype.dispose = function () {
  24879. if (!this._buffer) {
  24880. return;
  24881. }
  24882. if (this._engine._releaseBuffer(this._buffer)) {
  24883. this._buffer = null;
  24884. }
  24885. };
  24886. return UniformBuffer;
  24887. }());
  24888. // Pool for avoiding memory leaks
  24889. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24890. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24891. BABYLON.UniformBuffer = UniformBuffer;
  24892. })(BABYLON || (BABYLON = {}));
  24893. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24894. var BABYLON;
  24895. (function (BABYLON) {
  24896. var PushMaterial = (function (_super) {
  24897. __extends(PushMaterial, _super);
  24898. function PushMaterial(name, scene) {
  24899. var _this = _super.call(this, name, scene) || this;
  24900. _this.storeEffectOnSubMeshes = true;
  24901. return _this;
  24902. }
  24903. PushMaterial.prototype.getEffect = function () {
  24904. return this._activeEffect;
  24905. };
  24906. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24907. if (!mesh) {
  24908. return false;
  24909. }
  24910. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24911. return true;
  24912. }
  24913. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24914. };
  24915. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24916. this._activeEffect.setMatrix("world", world);
  24917. };
  24918. PushMaterial.prototype.bind = function (world, mesh) {
  24919. if (!mesh) {
  24920. return;
  24921. }
  24922. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24923. };
  24924. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24925. _super.prototype._afterBind.call(this, mesh);
  24926. this.getScene()._cachedEffect = effect;
  24927. };
  24928. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24929. if (visibility === void 0) { visibility = 0; }
  24930. return scene.isCachedMaterialValid(this, effect, visibility);
  24931. };
  24932. return PushMaterial;
  24933. }(BABYLON.Material));
  24934. BABYLON.PushMaterial = PushMaterial;
  24935. })(BABYLON || (BABYLON = {}));
  24936. //# sourceMappingURL=babylon.pushMaterial.js.map
  24937. var BABYLON;
  24938. (function (BABYLON) {
  24939. var VertexData = (function () {
  24940. function VertexData() {
  24941. }
  24942. VertexData.prototype.set = function (data, kind) {
  24943. switch (kind) {
  24944. case BABYLON.VertexBuffer.PositionKind:
  24945. this.positions = data;
  24946. break;
  24947. case BABYLON.VertexBuffer.NormalKind:
  24948. this.normals = data;
  24949. break;
  24950. case BABYLON.VertexBuffer.TangentKind:
  24951. this.tangents = data;
  24952. break;
  24953. case BABYLON.VertexBuffer.UVKind:
  24954. this.uvs = data;
  24955. break;
  24956. case BABYLON.VertexBuffer.UV2Kind:
  24957. this.uvs2 = data;
  24958. break;
  24959. case BABYLON.VertexBuffer.UV3Kind:
  24960. this.uvs3 = data;
  24961. break;
  24962. case BABYLON.VertexBuffer.UV4Kind:
  24963. this.uvs4 = data;
  24964. break;
  24965. case BABYLON.VertexBuffer.UV5Kind:
  24966. this.uvs5 = data;
  24967. break;
  24968. case BABYLON.VertexBuffer.UV6Kind:
  24969. this.uvs6 = data;
  24970. break;
  24971. case BABYLON.VertexBuffer.ColorKind:
  24972. this.colors = data;
  24973. break;
  24974. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24975. this.matricesIndices = data;
  24976. break;
  24977. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24978. this.matricesWeights = data;
  24979. break;
  24980. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24981. this.matricesIndicesExtra = data;
  24982. break;
  24983. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24984. this.matricesWeightsExtra = data;
  24985. break;
  24986. }
  24987. };
  24988. /**
  24989. * Associates the vertexData to the passed Mesh.
  24990. * Sets it as updatable or not (default `false`).
  24991. * Returns the VertexData.
  24992. */
  24993. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24994. this._applyTo(mesh, updatable);
  24995. return this;
  24996. };
  24997. /**
  24998. * Associates the vertexData to the passed Geometry.
  24999. * Sets it as updatable or not (default `false`).
  25000. * Returns the VertexData.
  25001. */
  25002. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25003. this._applyTo(geometry, updatable);
  25004. return this;
  25005. };
  25006. /**
  25007. * Updates the associated mesh.
  25008. * Returns the VertexData.
  25009. */
  25010. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25011. this._update(mesh);
  25012. return this;
  25013. };
  25014. /**
  25015. * Updates the associated geometry.
  25016. * Returns the VertexData.
  25017. */
  25018. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25019. this._update(geometry);
  25020. return this;
  25021. };
  25022. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25023. if (this.positions) {
  25024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25025. }
  25026. if (this.normals) {
  25027. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25028. }
  25029. if (this.tangents) {
  25030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25031. }
  25032. if (this.uvs) {
  25033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25034. }
  25035. if (this.uvs2) {
  25036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25037. }
  25038. if (this.uvs3) {
  25039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25040. }
  25041. if (this.uvs4) {
  25042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25043. }
  25044. if (this.uvs5) {
  25045. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25046. }
  25047. if (this.uvs6) {
  25048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25049. }
  25050. if (this.colors) {
  25051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25052. }
  25053. if (this.matricesIndices) {
  25054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25055. }
  25056. if (this.matricesWeights) {
  25057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25058. }
  25059. if (this.matricesIndicesExtra) {
  25060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25061. }
  25062. if (this.matricesWeightsExtra) {
  25063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25064. }
  25065. if (this.indices) {
  25066. meshOrGeometry.setIndices(this.indices);
  25067. }
  25068. return this;
  25069. };
  25070. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25071. if (this.positions) {
  25072. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25073. }
  25074. if (this.normals) {
  25075. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25076. }
  25077. if (this.tangents) {
  25078. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25079. }
  25080. if (this.uvs) {
  25081. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25082. }
  25083. if (this.uvs2) {
  25084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25085. }
  25086. if (this.uvs3) {
  25087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25088. }
  25089. if (this.uvs4) {
  25090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25091. }
  25092. if (this.uvs5) {
  25093. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25094. }
  25095. if (this.uvs6) {
  25096. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25097. }
  25098. if (this.colors) {
  25099. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25100. }
  25101. if (this.matricesIndices) {
  25102. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25103. }
  25104. if (this.matricesWeights) {
  25105. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25106. }
  25107. if (this.matricesIndicesExtra) {
  25108. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25109. }
  25110. if (this.matricesWeightsExtra) {
  25111. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25112. }
  25113. if (this.indices) {
  25114. meshOrGeometry.setIndices(this.indices);
  25115. }
  25116. return this;
  25117. };
  25118. /**
  25119. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25120. * Returns the VertexData.
  25121. */
  25122. VertexData.prototype.transform = function (matrix) {
  25123. var transformed = BABYLON.Vector3.Zero();
  25124. var index;
  25125. if (this.positions) {
  25126. var position = BABYLON.Vector3.Zero();
  25127. for (index = 0; index < this.positions.length; index += 3) {
  25128. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25129. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25130. this.positions[index] = transformed.x;
  25131. this.positions[index + 1] = transformed.y;
  25132. this.positions[index + 2] = transformed.z;
  25133. }
  25134. }
  25135. if (this.normals) {
  25136. var normal = BABYLON.Vector3.Zero();
  25137. for (index = 0; index < this.normals.length; index += 3) {
  25138. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25139. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25140. this.normals[index] = transformed.x;
  25141. this.normals[index + 1] = transformed.y;
  25142. this.normals[index + 2] = transformed.z;
  25143. }
  25144. }
  25145. if (this.tangents) {
  25146. var tangent = BABYLON.Vector4.Zero();
  25147. var tangentTransformed = BABYLON.Vector4.Zero();
  25148. for (index = 0; index < this.tangents.length; index += 4) {
  25149. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25150. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25151. this.tangents[index] = tangentTransformed.x;
  25152. this.tangents[index + 1] = tangentTransformed.y;
  25153. this.tangents[index + 2] = tangentTransformed.z;
  25154. this.tangents[index + 3] = tangentTransformed.w;
  25155. }
  25156. }
  25157. return this;
  25158. };
  25159. /**
  25160. * Merges the passed VertexData into the current one.
  25161. * Returns the modified VertexData.
  25162. */
  25163. VertexData.prototype.merge = function (other) {
  25164. if (other.indices) {
  25165. if (!this.indices) {
  25166. this.indices = [];
  25167. }
  25168. var offset = this.positions ? this.positions.length / 3 : 0;
  25169. for (var index = 0; index < other.indices.length; index++) {
  25170. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25171. this.indices.push(other.indices[index] + offset);
  25172. }
  25173. }
  25174. this.positions = this._mergeElement(this.positions, other.positions);
  25175. this.normals = this._mergeElement(this.normals, other.normals);
  25176. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25177. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25178. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25179. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25180. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25181. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25182. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25183. this.colors = this._mergeElement(this.colors, other.colors);
  25184. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25185. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25186. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25187. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25188. return this;
  25189. };
  25190. VertexData.prototype._mergeElement = function (source, other) {
  25191. if (!other)
  25192. return source;
  25193. if (!source)
  25194. return other;
  25195. var len = other.length + source.length;
  25196. var isSrcTypedArray = source instanceof Float32Array;
  25197. var isOthTypedArray = other instanceof Float32Array;
  25198. // use non-loop method when the source is Float32Array
  25199. if (isSrcTypedArray) {
  25200. var ret32 = new Float32Array(len);
  25201. ret32.set(source);
  25202. ret32.set(other, source.length);
  25203. return ret32;
  25204. // source is number[], when other is also use concat
  25205. }
  25206. else if (!isOthTypedArray) {
  25207. return source.concat(other);
  25208. // source is a number[], but other is a Float32Array, loop required
  25209. }
  25210. else {
  25211. var ret = source.slice(0); // copy source to a separate array
  25212. for (var i = 0, len = other.length; i < len; i++) {
  25213. ret.push(other[i]);
  25214. }
  25215. return ret;
  25216. }
  25217. };
  25218. /**
  25219. * Serializes the VertexData.
  25220. * Returns a serialized object.
  25221. */
  25222. VertexData.prototype.serialize = function () {
  25223. var serializationObject = this.serialize();
  25224. if (this.positions) {
  25225. serializationObject.positions = this.positions;
  25226. }
  25227. if (this.normals) {
  25228. serializationObject.normals = this.normals;
  25229. }
  25230. if (this.tangents) {
  25231. serializationObject.tangents = this.tangents;
  25232. }
  25233. if (this.uvs) {
  25234. serializationObject.uvs = this.uvs;
  25235. }
  25236. if (this.uvs2) {
  25237. serializationObject.uvs2 = this.uvs2;
  25238. }
  25239. if (this.uvs3) {
  25240. serializationObject.uvs3 = this.uvs3;
  25241. }
  25242. if (this.uvs4) {
  25243. serializationObject.uvs4 = this.uvs4;
  25244. }
  25245. if (this.uvs5) {
  25246. serializationObject.uvs5 = this.uvs5;
  25247. }
  25248. if (this.uvs6) {
  25249. serializationObject.uvs6 = this.uvs6;
  25250. }
  25251. if (this.colors) {
  25252. serializationObject.colors = this.colors;
  25253. }
  25254. if (this.matricesIndices) {
  25255. serializationObject.matricesIndices = this.matricesIndices;
  25256. serializationObject.matricesIndices._isExpanded = true;
  25257. }
  25258. if (this.matricesWeights) {
  25259. serializationObject.matricesWeights = this.matricesWeights;
  25260. }
  25261. if (this.matricesIndicesExtra) {
  25262. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25263. serializationObject.matricesIndicesExtra._isExpanded = true;
  25264. }
  25265. if (this.matricesWeightsExtra) {
  25266. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25267. }
  25268. serializationObject.indices = this.indices;
  25269. return serializationObject;
  25270. };
  25271. // Statics
  25272. /**
  25273. * Returns the object VertexData associated to the passed mesh.
  25274. */
  25275. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25276. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25277. };
  25278. /**
  25279. * Returns the object VertexData associated to the passed geometry.
  25280. */
  25281. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25282. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25283. };
  25284. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25285. var result = new VertexData();
  25286. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25287. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25288. }
  25289. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25290. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25291. }
  25292. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25293. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25294. }
  25295. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25296. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25297. }
  25298. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25299. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25300. }
  25301. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25302. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25303. }
  25304. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25305. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25306. }
  25307. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25308. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25309. }
  25310. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25311. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25312. }
  25313. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25314. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25315. }
  25316. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25317. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25318. }
  25319. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25320. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25321. }
  25322. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25323. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25324. }
  25325. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25326. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25327. }
  25328. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25329. return result;
  25330. };
  25331. /**
  25332. * Creates the vertexData of the Ribbon.
  25333. */
  25334. VertexData.CreateRibbon = function (options) {
  25335. var pathArray = options.pathArray;
  25336. var closeArray = options.closeArray || false;
  25337. var closePath = options.closePath || false;
  25338. var invertUV = options.invertUV || false;
  25339. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25340. var offset = options.offset || defaultOffset;
  25341. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25342. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25343. var customUV = options.uvs;
  25344. var customColors = options.colors;
  25345. var positions = [];
  25346. var indices = [];
  25347. var normals = [];
  25348. var uvs = [];
  25349. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25350. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25351. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25352. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25353. var minlg; // minimal length among all paths from pathArray
  25354. var lg = []; // array of path lengths : nb of vertex per path
  25355. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25356. var p; // path iterator
  25357. var i; // point iterator
  25358. var j; // point iterator
  25359. // if single path in pathArray
  25360. if (pathArray.length < 2) {
  25361. var ar1 = [];
  25362. var ar2 = [];
  25363. for (i = 0; i < pathArray[0].length - offset; i++) {
  25364. ar1.push(pathArray[0][i]);
  25365. ar2.push(pathArray[0][i + offset]);
  25366. }
  25367. pathArray = [ar1, ar2];
  25368. }
  25369. // positions and horizontal distances (u)
  25370. var idc = 0;
  25371. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25372. var path;
  25373. var l;
  25374. minlg = pathArray[0].length;
  25375. var vectlg;
  25376. var dist;
  25377. for (p = 0; p < pathArray.length; p++) {
  25378. uTotalDistance[p] = 0;
  25379. us[p] = [0];
  25380. path = pathArray[p];
  25381. l = path.length;
  25382. minlg = (minlg < l) ? minlg : l;
  25383. j = 0;
  25384. while (j < l) {
  25385. positions.push(path[j].x, path[j].y, path[j].z);
  25386. if (j > 0) {
  25387. vectlg = path[j].subtract(path[j - 1]).length();
  25388. dist = vectlg + uTotalDistance[p];
  25389. us[p].push(dist);
  25390. uTotalDistance[p] = dist;
  25391. }
  25392. j++;
  25393. }
  25394. if (closePath) {
  25395. j--;
  25396. positions.push(path[0].x, path[0].y, path[0].z);
  25397. vectlg = path[j].subtract(path[0]).length();
  25398. dist = vectlg + uTotalDistance[p];
  25399. us[p].push(dist);
  25400. uTotalDistance[p] = dist;
  25401. }
  25402. lg[p] = l + closePathCorr;
  25403. idx[p] = idc;
  25404. idc += (l + closePathCorr);
  25405. }
  25406. // vertical distances (v)
  25407. var path1;
  25408. var path2;
  25409. var vertex1;
  25410. var vertex2;
  25411. for (i = 0; i < minlg + closePathCorr; i++) {
  25412. vTotalDistance[i] = 0;
  25413. vs[i] = [0];
  25414. for (p = 0; p < pathArray.length - 1; p++) {
  25415. path1 = pathArray[p];
  25416. path2 = pathArray[p + 1];
  25417. if (i === minlg) {
  25418. vertex1 = path1[0];
  25419. vertex2 = path2[0];
  25420. }
  25421. else {
  25422. vertex1 = path1[i];
  25423. vertex2 = path2[i];
  25424. }
  25425. vectlg = vertex2.subtract(vertex1).length();
  25426. dist = vectlg + vTotalDistance[i];
  25427. vs[i].push(dist);
  25428. vTotalDistance[i] = dist;
  25429. }
  25430. if (closeArray) {
  25431. path1 = pathArray[p];
  25432. path2 = pathArray[0];
  25433. if (i === minlg) {
  25434. vertex2 = path2[0];
  25435. }
  25436. vectlg = vertex2.subtract(vertex1).length();
  25437. dist = vectlg + vTotalDistance[i];
  25438. vTotalDistance[i] = dist;
  25439. }
  25440. }
  25441. // uvs
  25442. var u;
  25443. var v;
  25444. if (customUV) {
  25445. for (p = 0; p < customUV.length; p++) {
  25446. uvs.push(customUV[p].x, customUV[p].y);
  25447. }
  25448. }
  25449. else {
  25450. for (p = 0; p < pathArray.length; p++) {
  25451. for (i = 0; i < minlg + closePathCorr; i++) {
  25452. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25453. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25454. if (invertUV) {
  25455. uvs.push(v, u);
  25456. }
  25457. else {
  25458. uvs.push(u, v);
  25459. }
  25460. }
  25461. }
  25462. }
  25463. // indices
  25464. p = 0; // path index
  25465. var pi = 0; // positions array index
  25466. var l1 = lg[p] - 1; // path1 length
  25467. var l2 = lg[p + 1] - 1; // path2 length
  25468. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25469. var shft = idx[1] - idx[0]; // shift
  25470. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25471. while (pi <= min && p < path1nb) {
  25472. // 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
  25473. indices.push(pi, pi + shft, pi + 1);
  25474. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25475. pi += 1;
  25476. if (pi === min) {
  25477. p++;
  25478. if (p === lg.length - 1) {
  25479. shft = idx[0] - idx[p];
  25480. l1 = lg[p] - 1;
  25481. l2 = lg[0] - 1;
  25482. }
  25483. else {
  25484. shft = idx[p + 1] - idx[p];
  25485. l1 = lg[p] - 1;
  25486. l2 = lg[p + 1] - 1;
  25487. }
  25488. pi = idx[p];
  25489. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25490. }
  25491. }
  25492. // normals
  25493. VertexData.ComputeNormals(positions, indices, normals);
  25494. if (closePath) {
  25495. var indexFirst = 0;
  25496. var indexLast = 0;
  25497. for (p = 0; p < pathArray.length; p++) {
  25498. indexFirst = idx[p] * 3;
  25499. if (p + 1 < pathArray.length) {
  25500. indexLast = (idx[p + 1] - 1) * 3;
  25501. }
  25502. else {
  25503. indexLast = normals.length - 3;
  25504. }
  25505. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25506. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25507. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25508. normals[indexLast] = normals[indexFirst];
  25509. normals[indexLast + 1] = normals[indexFirst + 1];
  25510. normals[indexLast + 2] = normals[indexFirst + 2];
  25511. }
  25512. }
  25513. // sides
  25514. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25515. // Colors
  25516. if (customColors) {
  25517. var colors = new Float32Array(customColors.length * 4);
  25518. for (var c = 0; c < customColors.length; c++) {
  25519. colors[c * 4] = customColors[c].r;
  25520. colors[c * 4 + 1] = customColors[c].g;
  25521. colors[c * 4 + 2] = customColors[c].b;
  25522. colors[c * 4 + 3] = customColors[c].a;
  25523. }
  25524. }
  25525. // Result
  25526. var vertexData = new VertexData();
  25527. var positions32 = new Float32Array(positions);
  25528. var normals32 = new Float32Array(normals);
  25529. var uvs32 = new Float32Array(uvs);
  25530. vertexData.indices = indices;
  25531. vertexData.positions = positions32;
  25532. vertexData.normals = normals32;
  25533. vertexData.uvs = uvs32;
  25534. if (customColors) {
  25535. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25536. }
  25537. if (closePath) {
  25538. vertexData._idx = idx;
  25539. }
  25540. return vertexData;
  25541. };
  25542. /**
  25543. * Creates the VertexData of the Box.
  25544. */
  25545. VertexData.CreateBox = function (options) {
  25546. var normalsSource = [
  25547. new BABYLON.Vector3(0, 0, 1),
  25548. new BABYLON.Vector3(0, 0, -1),
  25549. new BABYLON.Vector3(1, 0, 0),
  25550. new BABYLON.Vector3(-1, 0, 0),
  25551. new BABYLON.Vector3(0, 1, 0),
  25552. new BABYLON.Vector3(0, -1, 0)
  25553. ];
  25554. var indices = [];
  25555. var positions = [];
  25556. var normals = [];
  25557. var uvs = [];
  25558. var width = options.width || options.size || 1;
  25559. var height = options.height || options.size || 1;
  25560. var depth = options.depth || options.size || 1;
  25561. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25562. var faceUV = options.faceUV || new Array(6);
  25563. var faceColors = options.faceColors;
  25564. var colors = [];
  25565. // default face colors and UV if undefined
  25566. for (var f = 0; f < 6; f++) {
  25567. if (faceUV[f] === undefined) {
  25568. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25569. }
  25570. if (faceColors && faceColors[f] === undefined) {
  25571. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25572. }
  25573. }
  25574. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25575. // Create each face in turn.
  25576. for (var index = 0; index < normalsSource.length; index++) {
  25577. var normal = normalsSource[index];
  25578. // Get two vectors perpendicular to the face normal and to each other.
  25579. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25580. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25581. // Six indices (two triangles) per face.
  25582. var verticesLength = positions.length / 3;
  25583. indices.push(verticesLength);
  25584. indices.push(verticesLength + 1);
  25585. indices.push(verticesLength + 2);
  25586. indices.push(verticesLength);
  25587. indices.push(verticesLength + 2);
  25588. indices.push(verticesLength + 3);
  25589. // Four vertices per face.
  25590. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25591. positions.push(vertex.x, vertex.y, vertex.z);
  25592. normals.push(normal.x, normal.y, normal.z);
  25593. uvs.push(faceUV[index].z, faceUV[index].w);
  25594. if (faceColors) {
  25595. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25596. }
  25597. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25598. positions.push(vertex.x, vertex.y, vertex.z);
  25599. normals.push(normal.x, normal.y, normal.z);
  25600. uvs.push(faceUV[index].x, faceUV[index].w);
  25601. if (faceColors) {
  25602. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25603. }
  25604. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25605. positions.push(vertex.x, vertex.y, vertex.z);
  25606. normals.push(normal.x, normal.y, normal.z);
  25607. uvs.push(faceUV[index].x, faceUV[index].y);
  25608. if (faceColors) {
  25609. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25610. }
  25611. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25612. positions.push(vertex.x, vertex.y, vertex.z);
  25613. normals.push(normal.x, normal.y, normal.z);
  25614. uvs.push(faceUV[index].z, faceUV[index].y);
  25615. if (faceColors) {
  25616. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25617. }
  25618. }
  25619. // sides
  25620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25621. // Result
  25622. var vertexData = new VertexData();
  25623. vertexData.indices = indices;
  25624. vertexData.positions = positions;
  25625. vertexData.normals = normals;
  25626. vertexData.uvs = uvs;
  25627. if (faceColors) {
  25628. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25629. vertexData.colors = totalColors;
  25630. }
  25631. return vertexData;
  25632. };
  25633. /**
  25634. * Creates the VertexData of the Sphere.
  25635. */
  25636. VertexData.CreateSphere = function (options) {
  25637. var segments = options.segments || 32;
  25638. var diameterX = options.diameterX || options.diameter || 1;
  25639. var diameterY = options.diameterY || options.diameter || 1;
  25640. var diameterZ = options.diameterZ || options.diameter || 1;
  25641. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25642. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25643. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25644. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25645. var totalZRotationSteps = 2 + segments;
  25646. var totalYRotationSteps = 2 * totalZRotationSteps;
  25647. var indices = [];
  25648. var positions = [];
  25649. var normals = [];
  25650. var uvs = [];
  25651. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25652. var normalizedZ = zRotationStep / totalZRotationSteps;
  25653. var angleZ = normalizedZ * Math.PI * slice;
  25654. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25655. var normalizedY = yRotationStep / totalYRotationSteps;
  25656. var angleY = normalizedY * Math.PI * 2 * arc;
  25657. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25658. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25659. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25660. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25661. var vertex = complete.multiply(radius);
  25662. var normal = complete.divide(radius).normalize();
  25663. positions.push(vertex.x, vertex.y, vertex.z);
  25664. normals.push(normal.x, normal.y, normal.z);
  25665. uvs.push(normalizedY, normalizedZ);
  25666. }
  25667. if (zRotationStep > 0) {
  25668. var verticesCount = positions.length / 3;
  25669. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25670. indices.push((firstIndex));
  25671. indices.push((firstIndex + 1));
  25672. indices.push(firstIndex + totalYRotationSteps + 1);
  25673. indices.push((firstIndex + totalYRotationSteps + 1));
  25674. indices.push((firstIndex + 1));
  25675. indices.push((firstIndex + totalYRotationSteps + 2));
  25676. }
  25677. }
  25678. }
  25679. // Sides
  25680. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25681. // Result
  25682. var vertexData = new VertexData();
  25683. vertexData.indices = indices;
  25684. vertexData.positions = positions;
  25685. vertexData.normals = normals;
  25686. vertexData.uvs = uvs;
  25687. return vertexData;
  25688. };
  25689. /**
  25690. * Creates the VertexData of the Cylinder or Cone.
  25691. */
  25692. VertexData.CreateCylinder = function (options) {
  25693. var height = options.height || 2;
  25694. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25695. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25696. var tessellation = options.tessellation || 24;
  25697. var subdivisions = options.subdivisions || 1;
  25698. var hasRings = options.hasRings;
  25699. var enclose = options.enclose;
  25700. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25701. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25702. var faceUV = options.faceUV || new Array(3);
  25703. var faceColors = options.faceColors;
  25704. // default face colors and UV if undefined
  25705. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25706. var ringNb = (hasRings) ? subdivisions : 1;
  25707. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25708. var f;
  25709. for (f = 0; f < surfaceNb; f++) {
  25710. if (faceColors && faceColors[f] === undefined) {
  25711. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25712. }
  25713. }
  25714. for (f = 0; f < surfaceNb; f++) {
  25715. if (faceUV && faceUV[f] === undefined) {
  25716. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25717. }
  25718. }
  25719. var indices = [];
  25720. var positions = [];
  25721. var normals = [];
  25722. var uvs = [];
  25723. var colors = [];
  25724. var angle_step = Math.PI * 2 * arc / tessellation;
  25725. var angle;
  25726. var h;
  25727. var radius;
  25728. var tan = (diameterBottom - diameterTop) / 2 / height;
  25729. var ringVertex = BABYLON.Vector3.Zero();
  25730. var ringNormal = BABYLON.Vector3.Zero();
  25731. var ringFirstVertex = BABYLON.Vector3.Zero();
  25732. var ringFirstNormal = BABYLON.Vector3.Zero();
  25733. var quadNormal = BABYLON.Vector3.Zero();
  25734. var Y = BABYLON.Axis.Y;
  25735. // positions, normals, uvs
  25736. var i;
  25737. var j;
  25738. var r;
  25739. var ringIdx = 1;
  25740. var s = 1; // surface index
  25741. var cs = 0;
  25742. var v = 0;
  25743. for (i = 0; i <= subdivisions; i++) {
  25744. h = i / subdivisions;
  25745. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25746. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25747. for (r = 0; r < ringIdx; r++) {
  25748. if (hasRings) {
  25749. s += r;
  25750. }
  25751. if (enclose) {
  25752. s += 2 * r;
  25753. }
  25754. for (j = 0; j <= tessellation; j++) {
  25755. angle = j * angle_step;
  25756. // position
  25757. ringVertex.x = Math.cos(-angle) * radius;
  25758. ringVertex.y = -height / 2 + h * height;
  25759. ringVertex.z = Math.sin(-angle) * radius;
  25760. // normal
  25761. if (diameterTop === 0 && i === subdivisions) {
  25762. // if no top cap, reuse former normals
  25763. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25764. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25765. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25766. }
  25767. else {
  25768. ringNormal.x = ringVertex.x;
  25769. ringNormal.z = ringVertex.z;
  25770. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25771. ringNormal.normalize();
  25772. }
  25773. // keep first ring vertex values for enclose
  25774. if (j === 0) {
  25775. ringFirstVertex.copyFrom(ringVertex);
  25776. ringFirstNormal.copyFrom(ringNormal);
  25777. }
  25778. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25779. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25780. if (hasRings) {
  25781. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25782. }
  25783. else {
  25784. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25785. }
  25786. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25787. if (faceColors) {
  25788. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25789. }
  25790. }
  25791. // if enclose, add four vertices and their dedicated normals
  25792. if (arc !== 1 && enclose) {
  25793. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25794. positions.push(0, ringVertex.y, 0);
  25795. positions.push(0, ringVertex.y, 0);
  25796. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25797. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25798. quadNormal.normalize();
  25799. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25800. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25801. quadNormal.normalize();
  25802. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25803. if (hasRings) {
  25804. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25805. }
  25806. else {
  25807. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25808. }
  25809. uvs.push(faceUV[s + 1].x, v);
  25810. uvs.push(faceUV[s + 1].z, v);
  25811. if (hasRings) {
  25812. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25813. }
  25814. else {
  25815. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25816. }
  25817. uvs.push(faceUV[s + 2].x, v);
  25818. uvs.push(faceUV[s + 2].z, v);
  25819. if (faceColors) {
  25820. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25821. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25822. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25823. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25824. }
  25825. }
  25826. if (cs !== s) {
  25827. cs = s;
  25828. }
  25829. }
  25830. }
  25831. // indices
  25832. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25833. var s;
  25834. i = 0;
  25835. for (s = 0; s < subdivisions; s++) {
  25836. for (j = 0; j < tessellation; j++) {
  25837. var i0 = i * (e + 1) + j;
  25838. var i1 = (i + 1) * (e + 1) + j;
  25839. var i2 = i * (e + 1) + (j + 1);
  25840. var i3 = (i + 1) * (e + 1) + (j + 1);
  25841. indices.push(i0, i1, i2);
  25842. indices.push(i3, i2, i1);
  25843. }
  25844. if (arc !== 1 && enclose) {
  25845. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25846. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25847. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25848. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25849. }
  25850. i = (hasRings) ? (i + 2) : (i + 1);
  25851. }
  25852. // Caps
  25853. var createCylinderCap = function (isTop) {
  25854. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25855. if (radius === 0) {
  25856. return;
  25857. }
  25858. // Cap positions, normals & uvs
  25859. var angle;
  25860. var circleVector;
  25861. var i;
  25862. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25863. var c;
  25864. if (faceColors) {
  25865. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25866. }
  25867. // cap center
  25868. var vbase = positions.length / 3;
  25869. var offset = isTop ? height / 2 : -height / 2;
  25870. var center = new BABYLON.Vector3(0, offset, 0);
  25871. positions.push(center.x, center.y, center.z);
  25872. normals.push(0, isTop ? 1 : -1, 0);
  25873. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25874. if (faceColors) {
  25875. colors.push(c.r, c.g, c.b, c.a);
  25876. }
  25877. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25878. for (i = 0; i <= tessellation; i++) {
  25879. angle = Math.PI * 2 * i * arc / tessellation;
  25880. var cos = Math.cos(-angle);
  25881. var sin = Math.sin(-angle);
  25882. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25883. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25884. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25885. normals.push(0, isTop ? 1 : -1, 0);
  25886. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25887. if (faceColors) {
  25888. colors.push(c.r, c.g, c.b, c.a);
  25889. }
  25890. }
  25891. // Cap indices
  25892. for (i = 0; i < tessellation; i++) {
  25893. if (!isTop) {
  25894. indices.push(vbase);
  25895. indices.push(vbase + (i + 1));
  25896. indices.push(vbase + (i + 2));
  25897. }
  25898. else {
  25899. indices.push(vbase);
  25900. indices.push(vbase + (i + 2));
  25901. indices.push(vbase + (i + 1));
  25902. }
  25903. }
  25904. };
  25905. // add caps to geometry
  25906. createCylinderCap(false);
  25907. createCylinderCap(true);
  25908. // Sides
  25909. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25910. var vertexData = new VertexData();
  25911. vertexData.indices = indices;
  25912. vertexData.positions = positions;
  25913. vertexData.normals = normals;
  25914. vertexData.uvs = uvs;
  25915. if (faceColors) {
  25916. vertexData.colors = colors;
  25917. }
  25918. return vertexData;
  25919. };
  25920. /**
  25921. * Creates the VertexData of the Torus.
  25922. */
  25923. VertexData.CreateTorus = function (options) {
  25924. var indices = [];
  25925. var positions = [];
  25926. var normals = [];
  25927. var uvs = [];
  25928. var diameter = options.diameter || 1;
  25929. var thickness = options.thickness || 0.5;
  25930. var tessellation = options.tessellation || 16;
  25931. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25932. var stride = tessellation + 1;
  25933. for (var i = 0; i <= tessellation; i++) {
  25934. var u = i / tessellation;
  25935. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25936. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25937. for (var j = 0; j <= tessellation; j++) {
  25938. var v = 1 - j / tessellation;
  25939. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25940. var dx = Math.cos(innerAngle);
  25941. var dy = Math.sin(innerAngle);
  25942. // Create a vertex.
  25943. var normal = new BABYLON.Vector3(dx, dy, 0);
  25944. var position = normal.scale(thickness / 2);
  25945. var textureCoordinate = new BABYLON.Vector2(u, v);
  25946. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25947. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25948. positions.push(position.x, position.y, position.z);
  25949. normals.push(normal.x, normal.y, normal.z);
  25950. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25951. // And create indices for two triangles.
  25952. var nextI = (i + 1) % stride;
  25953. var nextJ = (j + 1) % stride;
  25954. indices.push(i * stride + j);
  25955. indices.push(i * stride + nextJ);
  25956. indices.push(nextI * stride + j);
  25957. indices.push(i * stride + nextJ);
  25958. indices.push(nextI * stride + nextJ);
  25959. indices.push(nextI * stride + j);
  25960. }
  25961. }
  25962. // Sides
  25963. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25964. // Result
  25965. var vertexData = new VertexData();
  25966. vertexData.indices = indices;
  25967. vertexData.positions = positions;
  25968. vertexData.normals = normals;
  25969. vertexData.uvs = uvs;
  25970. return vertexData;
  25971. };
  25972. /**
  25973. * Creates the VertexData of the LineSystem.
  25974. */
  25975. VertexData.CreateLineSystem = function (options) {
  25976. var indices = [];
  25977. var positions = [];
  25978. var lines = options.lines;
  25979. var idx = 0;
  25980. for (var l = 0; l < lines.length; l++) {
  25981. var points = lines[l];
  25982. for (var index = 0; index < points.length; index++) {
  25983. positions.push(points[index].x, points[index].y, points[index].z);
  25984. if (index > 0) {
  25985. indices.push(idx - 1);
  25986. indices.push(idx);
  25987. }
  25988. idx++;
  25989. }
  25990. }
  25991. var vertexData = new VertexData();
  25992. vertexData.indices = indices;
  25993. vertexData.positions = positions;
  25994. return vertexData;
  25995. };
  25996. /**
  25997. * Create the VertexData of the DashedLines.
  25998. */
  25999. VertexData.CreateDashedLines = function (options) {
  26000. var dashSize = options.dashSize || 3;
  26001. var gapSize = options.gapSize || 1;
  26002. var dashNb = options.dashNb || 200;
  26003. var points = options.points;
  26004. var positions = new Array();
  26005. var indices = new Array();
  26006. var curvect = BABYLON.Vector3.Zero();
  26007. var lg = 0;
  26008. var nb = 0;
  26009. var shft = 0;
  26010. var dashshft = 0;
  26011. var curshft = 0;
  26012. var idx = 0;
  26013. var i = 0;
  26014. for (i = 0; i < points.length - 1; i++) {
  26015. points[i + 1].subtractToRef(points[i], curvect);
  26016. lg += curvect.length();
  26017. }
  26018. shft = lg / dashNb;
  26019. dashshft = dashSize * shft / (dashSize + gapSize);
  26020. for (i = 0; i < points.length - 1; i++) {
  26021. points[i + 1].subtractToRef(points[i], curvect);
  26022. nb = Math.floor(curvect.length() / shft);
  26023. curvect.normalize();
  26024. for (var j = 0; j < nb; j++) {
  26025. curshft = shft * j;
  26026. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26027. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26028. indices.push(idx, idx + 1);
  26029. idx += 2;
  26030. }
  26031. }
  26032. // Result
  26033. var vertexData = new VertexData();
  26034. vertexData.positions = positions;
  26035. vertexData.indices = indices;
  26036. return vertexData;
  26037. };
  26038. /**
  26039. * Creates the VertexData of the Ground.
  26040. */
  26041. VertexData.CreateGround = function (options) {
  26042. var indices = [];
  26043. var positions = [];
  26044. var normals = [];
  26045. var uvs = [];
  26046. var row, col;
  26047. var width = options.width || 1;
  26048. var height = options.height || 1;
  26049. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26050. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26051. for (row = 0; row <= subdivisionsY; row++) {
  26052. for (col = 0; col <= subdivisionsX; col++) {
  26053. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26054. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26055. positions.push(position.x, position.y, position.z);
  26056. normals.push(normal.x, normal.y, normal.z);
  26057. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26058. }
  26059. }
  26060. for (row = 0; row < subdivisionsY; row++) {
  26061. for (col = 0; col < subdivisionsX; col++) {
  26062. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26063. indices.push(col + 1 + row * (subdivisionsX + 1));
  26064. indices.push(col + row * (subdivisionsX + 1));
  26065. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26066. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26067. indices.push(col + row * (subdivisionsX + 1));
  26068. }
  26069. }
  26070. // Result
  26071. var vertexData = new VertexData();
  26072. vertexData.indices = indices;
  26073. vertexData.positions = positions;
  26074. vertexData.normals = normals;
  26075. vertexData.uvs = uvs;
  26076. return vertexData;
  26077. };
  26078. /**
  26079. * Creates the VertexData of the TiledGround.
  26080. */
  26081. VertexData.CreateTiledGround = function (options) {
  26082. var xmin = options.xmin || -1.0;
  26083. var zmin = options.zmin || -1.0;
  26084. var xmax = options.xmax || 1.0;
  26085. var zmax = options.zmax || 1.0;
  26086. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26087. var precision = options.precision || { w: 1, h: 1 };
  26088. var indices = [];
  26089. var positions = [];
  26090. var normals = [];
  26091. var uvs = [];
  26092. var row, col, tileRow, tileCol;
  26093. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26094. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26095. precision.w = (precision.w < 1) ? 1 : precision.w;
  26096. precision.h = (precision.h < 1) ? 1 : precision.h;
  26097. var tileSize = {
  26098. 'w': (xmax - xmin) / subdivisions.w,
  26099. 'h': (zmax - zmin) / subdivisions.h
  26100. };
  26101. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26102. // Indices
  26103. var base = positions.length / 3;
  26104. var rowLength = precision.w + 1;
  26105. for (row = 0; row < precision.h; row++) {
  26106. for (col = 0; col < precision.w; col++) {
  26107. var square = [
  26108. base + col + row * rowLength,
  26109. base + (col + 1) + row * rowLength,
  26110. base + (col + 1) + (row + 1) * rowLength,
  26111. base + col + (row + 1) * rowLength
  26112. ];
  26113. indices.push(square[1]);
  26114. indices.push(square[2]);
  26115. indices.push(square[3]);
  26116. indices.push(square[0]);
  26117. indices.push(square[1]);
  26118. indices.push(square[3]);
  26119. }
  26120. }
  26121. // Position, normals and uvs
  26122. var position = BABYLON.Vector3.Zero();
  26123. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26124. for (row = 0; row <= precision.h; row++) {
  26125. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26126. for (col = 0; col <= precision.w; col++) {
  26127. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26128. position.y = 0;
  26129. positions.push(position.x, position.y, position.z);
  26130. normals.push(normal.x, normal.y, normal.z);
  26131. uvs.push(col / precision.w, row / precision.h);
  26132. }
  26133. }
  26134. }
  26135. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26136. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26137. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26138. }
  26139. }
  26140. // Result
  26141. var vertexData = new VertexData();
  26142. vertexData.indices = indices;
  26143. vertexData.positions = positions;
  26144. vertexData.normals = normals;
  26145. vertexData.uvs = uvs;
  26146. return vertexData;
  26147. };
  26148. /**
  26149. * Creates the VertexData of the Ground designed from a heightmap.
  26150. */
  26151. VertexData.CreateGroundFromHeightMap = function (options) {
  26152. var indices = [];
  26153. var positions = [];
  26154. var normals = [];
  26155. var uvs = [];
  26156. var row, col;
  26157. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26158. // Vertices
  26159. for (row = 0; row <= options.subdivisions; row++) {
  26160. for (col = 0; col <= options.subdivisions; col++) {
  26161. 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));
  26162. // Compute height
  26163. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26164. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26165. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26166. var r = options.buffer[pos] / 255.0;
  26167. var g = options.buffer[pos + 1] / 255.0;
  26168. var b = options.buffer[pos + 2] / 255.0;
  26169. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26170. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26171. // Add vertex
  26172. positions.push(position.x, position.y, position.z);
  26173. normals.push(0, 0, 0);
  26174. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26175. }
  26176. }
  26177. // Indices
  26178. for (row = 0; row < options.subdivisions; row++) {
  26179. for (col = 0; col < options.subdivisions; col++) {
  26180. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26181. indices.push(col + 1 + row * (options.subdivisions + 1));
  26182. indices.push(col + row * (options.subdivisions + 1));
  26183. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26184. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26185. indices.push(col + row * (options.subdivisions + 1));
  26186. }
  26187. }
  26188. // Normals
  26189. VertexData.ComputeNormals(positions, indices, normals);
  26190. // Result
  26191. var vertexData = new VertexData();
  26192. vertexData.indices = indices;
  26193. vertexData.positions = positions;
  26194. vertexData.normals = normals;
  26195. vertexData.uvs = uvs;
  26196. return vertexData;
  26197. };
  26198. /**
  26199. * Creates the VertexData of the Plane.
  26200. */
  26201. VertexData.CreatePlane = function (options) {
  26202. var indices = [];
  26203. var positions = [];
  26204. var normals = [];
  26205. var uvs = [];
  26206. var width = options.width || options.size || 1;
  26207. var height = options.height || options.size || 1;
  26208. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26209. // Vertices
  26210. var halfWidth = width / 2.0;
  26211. var halfHeight = height / 2.0;
  26212. positions.push(-halfWidth, -halfHeight, 0);
  26213. normals.push(0, 0, -1.0);
  26214. uvs.push(0.0, 0.0);
  26215. positions.push(halfWidth, -halfHeight, 0);
  26216. normals.push(0, 0, -1.0);
  26217. uvs.push(1.0, 0.0);
  26218. positions.push(halfWidth, halfHeight, 0);
  26219. normals.push(0, 0, -1.0);
  26220. uvs.push(1.0, 1.0);
  26221. positions.push(-halfWidth, halfHeight, 0);
  26222. normals.push(0, 0, -1.0);
  26223. uvs.push(0.0, 1.0);
  26224. // Indices
  26225. indices.push(0);
  26226. indices.push(1);
  26227. indices.push(2);
  26228. indices.push(0);
  26229. indices.push(2);
  26230. indices.push(3);
  26231. // Sides
  26232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26233. // Result
  26234. var vertexData = new VertexData();
  26235. vertexData.indices = indices;
  26236. vertexData.positions = positions;
  26237. vertexData.normals = normals;
  26238. vertexData.uvs = uvs;
  26239. return vertexData;
  26240. };
  26241. /**
  26242. * Creates the VertexData of the Disc or regular Polygon.
  26243. */
  26244. VertexData.CreateDisc = function (options) {
  26245. var positions = [];
  26246. var indices = [];
  26247. var normals = [];
  26248. var uvs = [];
  26249. var radius = options.radius || 0.5;
  26250. var tessellation = options.tessellation || 64;
  26251. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26252. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26253. // positions and uvs
  26254. positions.push(0, 0, 0); // disc center first
  26255. uvs.push(0.5, 0.5);
  26256. var theta = Math.PI * 2 * arc;
  26257. var step = theta / tessellation;
  26258. for (var a = 0; a < theta; a += step) {
  26259. var x = Math.cos(a);
  26260. var y = Math.sin(a);
  26261. var u = (x + 1) / 2;
  26262. var v = (1 - y) / 2;
  26263. positions.push(radius * x, radius * y, 0);
  26264. uvs.push(u, v);
  26265. }
  26266. if (arc === 1) {
  26267. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26268. uvs.push(uvs[2], uvs[3]);
  26269. }
  26270. //indices
  26271. var vertexNb = positions.length / 3;
  26272. for (var i = 1; i < vertexNb - 1; i++) {
  26273. indices.push(i + 1, 0, i);
  26274. }
  26275. // result
  26276. VertexData.ComputeNormals(positions, indices, normals);
  26277. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26278. var vertexData = new VertexData();
  26279. vertexData.indices = indices;
  26280. vertexData.positions = positions;
  26281. vertexData.normals = normals;
  26282. vertexData.uvs = uvs;
  26283. return vertexData;
  26284. };
  26285. /**
  26286. * Re-creates the VertexData of the Polygon for sideOrientation.
  26287. */
  26288. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26289. var faceUV = fUV || new Array(3);
  26290. var faceColors = fColors;
  26291. var colors = [];
  26292. // default face colors and UV if undefined
  26293. for (var f = 0; f < 3; f++) {
  26294. if (faceUV[f] === undefined) {
  26295. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26296. }
  26297. if (faceColors && faceColors[f] === undefined) {
  26298. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26299. }
  26300. }
  26301. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26302. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26303. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26304. var indices = polygon.getIndices();
  26305. // set face colours and textures
  26306. var idx = 0;
  26307. var face = 0;
  26308. for (var index = 0; index < normals.length; index += 3) {
  26309. //Edge Face no. 1
  26310. if (Math.abs(normals[index + 1]) == 0) {
  26311. face = 1;
  26312. }
  26313. //Top Face no. 0
  26314. if (normals[index + 1] == 1) {
  26315. face = 0;
  26316. }
  26317. //Bottom Face no. 2
  26318. if (normals[index + 1] == -1) {
  26319. face = 2;
  26320. }
  26321. idx = index / 3;
  26322. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26323. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26324. if (faceColors) {
  26325. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26326. }
  26327. }
  26328. // sides
  26329. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26330. // Result
  26331. var vertexData = new VertexData();
  26332. vertexData.indices = indices;
  26333. vertexData.positions = positions;
  26334. vertexData.normals = normals;
  26335. vertexData.uvs = uvs;
  26336. if (faceColors) {
  26337. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26338. vertexData.colors = totalColors;
  26339. }
  26340. return vertexData;
  26341. };
  26342. /**
  26343. * Creates the VertexData of the IcoSphere.
  26344. */
  26345. VertexData.CreateIcoSphere = function (options) {
  26346. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26347. var radius = options.radius || 1;
  26348. var flat = (options.flat === undefined) ? true : options.flat;
  26349. var subdivisions = options.subdivisions || 4;
  26350. var radiusX = options.radiusX || radius;
  26351. var radiusY = options.radiusY || radius;
  26352. var radiusZ = options.radiusZ || radius;
  26353. var t = (1 + Math.sqrt(5)) / 2;
  26354. // 12 vertex x,y,z
  26355. var ico_vertices = [
  26356. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26357. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26358. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26359. ];
  26360. // index of 3 vertex makes a face of icopshere
  26361. var ico_indices = [
  26362. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26363. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26364. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26365. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26366. ];
  26367. // vertex for uv have aliased position, not for UV
  26368. var vertices_unalias_id = [
  26369. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26370. // vertex alias
  26371. 0,
  26372. 2,
  26373. 3,
  26374. 3,
  26375. 3,
  26376. 4,
  26377. 7,
  26378. 8,
  26379. 9,
  26380. 9,
  26381. 10,
  26382. 11 // 23: B + 12
  26383. ];
  26384. // uv as integer step (not pixels !)
  26385. var ico_vertexuv = [
  26386. 5, 1, 3, 1, 6, 4, 0, 0,
  26387. 5, 3, 4, 2, 2, 2, 4, 0,
  26388. 2, 0, 1, 1, 6, 0, 6, 2,
  26389. // vertex alias (for same vertex on different faces)
  26390. 0, 4,
  26391. 3, 3,
  26392. 4, 4,
  26393. 3, 1,
  26394. 4, 2,
  26395. 4, 4,
  26396. 0, 2,
  26397. 1, 1,
  26398. 2, 2,
  26399. 3, 3,
  26400. 1, 3,
  26401. 2, 4 // 23: B + 12
  26402. ];
  26403. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26404. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26405. // First island of uv mapping
  26406. // v = 4h 3+ 2
  26407. // v = 3h 9+ 4
  26408. // v = 2h 9+ 5 B
  26409. // v = 1h 9 1 0
  26410. // v = 0h 3 8 7 A
  26411. // u = 0 1 2 3 4 5 6 *a
  26412. // Second island of uv mapping
  26413. // v = 4h 0+ B+ 4+
  26414. // v = 3h A+ 2+
  26415. // v = 2h 7+ 6 3+
  26416. // v = 1h 8+ 3+
  26417. // v = 0h
  26418. // u = 0 1 2 3 4 5 6 *a
  26419. // Face layout on texture UV mapping
  26420. // ============
  26421. // \ 4 /\ 16 / ======
  26422. // \ / \ / /\ 11 /
  26423. // \/ 7 \/ / \ /
  26424. // ======= / 10 \/
  26425. // /\ 17 /\ =======
  26426. // / \ / \ \ 15 /\
  26427. // / 8 \/ 12 \ \ / \
  26428. // ============ \/ 6 \
  26429. // \ 18 /\ ============
  26430. // \ / \ \ 5 /\ 0 /
  26431. // \/ 13 \ \ / \ /
  26432. // ======= \/ 1 \/
  26433. // =============
  26434. // /\ 19 /\ 2 /\
  26435. // / \ / \ / \
  26436. // / 14 \/ 9 \/ 3 \
  26437. // ===================
  26438. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26439. var ustep = 138 / 1024;
  26440. var vstep = 239 / 1024;
  26441. var uoffset = 60 / 1024;
  26442. var voffset = 26 / 1024;
  26443. // Second island should have margin, not to touch the first island
  26444. // avoid any borderline artefact in pixel rounding
  26445. var island_u_offset = -40 / 1024;
  26446. var island_v_offset = +20 / 1024;
  26447. // face is either island 0 or 1 :
  26448. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26449. var island = [
  26450. 0, 0, 0, 0, 1,
  26451. 0, 0, 1, 1, 0,
  26452. 0, 0, 1, 1, 0,
  26453. 0, 1, 1, 1, 0 // 15 - 19
  26454. ];
  26455. var indices = [];
  26456. var positions = [];
  26457. var normals = [];
  26458. var uvs = [];
  26459. var current_indice = 0;
  26460. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26461. var face_vertex_pos = new Array(3);
  26462. var face_vertex_uv = new Array(3);
  26463. var v012;
  26464. for (v012 = 0; v012 < 3; v012++) {
  26465. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26466. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26467. }
  26468. // create all with normals
  26469. for (var face = 0; face < 20; face++) {
  26470. // 3 vertex per face
  26471. for (v012 = 0; v012 < 3; v012++) {
  26472. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26473. var v_id = ico_indices[3 * face + v012];
  26474. // vertex have 3D position (x,y,z)
  26475. 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]);
  26476. // Normalize to get normal, then scale to radius
  26477. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26478. // uv Coordinates from vertex ID
  26479. 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);
  26480. }
  26481. // Subdivide the face (interpolate pos, norm, uv)
  26482. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26483. // - norm is linear interpolation of vertex corner normal
  26484. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26485. // - uv is linear interpolation
  26486. //
  26487. // Topology is as below for sub-divide by 2
  26488. // vertex shown as v0,v1,v2
  26489. // interp index is i1 to progress in range [v0,v1[
  26490. // interp index is i2 to progress in range [v0,v2[
  26491. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26492. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26493. //
  26494. //
  26495. // i2 v2
  26496. // ^ ^
  26497. // / / \
  26498. // / / \
  26499. // / / \
  26500. // / / (0,1) \
  26501. // / #---------\
  26502. // / / \ (0,0)'/ \
  26503. // / / \ / \
  26504. // / / \ / \
  26505. // / / (0,0) \ / (1,0) \
  26506. // / #---------#---------\
  26507. // v0 v1
  26508. //
  26509. // --------------------> i1
  26510. //
  26511. // interp of (i1,i2):
  26512. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26513. // along i1 : lerp(x0,x1, i1/(S-i2))
  26514. //
  26515. // centroid of triangle is needed to get help normal computation
  26516. // (c1,c2) are used for centroid location
  26517. var interp_vertex = function (i1, i2, c1, c2) {
  26518. // vertex is interpolated from
  26519. // - face_vertex_pos[0..2]
  26520. // - face_vertex_uv[0..2]
  26521. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26522. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26523. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26524. pos_interp.normalize();
  26525. var vertex_normal;
  26526. if (flat) {
  26527. // in flat mode, recalculate normal as face centroid normal
  26528. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26529. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26530. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26531. }
  26532. else {
  26533. // in smooth mode, recalculate normal from each single vertex position
  26534. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26535. }
  26536. // Vertex normal need correction due to X,Y,Z radius scaling
  26537. vertex_normal.x /= radiusX;
  26538. vertex_normal.y /= radiusY;
  26539. vertex_normal.z /= radiusZ;
  26540. vertex_normal.normalize();
  26541. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26542. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26543. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26544. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26545. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26546. uvs.push(uv_interp.x, uv_interp.y);
  26547. // push each vertex has member of a face
  26548. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26549. indices.push(current_indice);
  26550. current_indice++;
  26551. };
  26552. for (var i2 = 0; i2 < subdivisions; i2++) {
  26553. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26554. // face : (i1,i2) for /\ :
  26555. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26556. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26557. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26558. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26559. if (i1 + i2 + 1 < subdivisions) {
  26560. // face : (i1,i2)' for \/ :
  26561. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26562. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26563. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26564. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26565. }
  26566. }
  26567. }
  26568. }
  26569. // Sides
  26570. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26571. // Result
  26572. var vertexData = new VertexData();
  26573. vertexData.indices = indices;
  26574. vertexData.positions = positions;
  26575. vertexData.normals = normals;
  26576. vertexData.uvs = uvs;
  26577. return vertexData;
  26578. };
  26579. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26580. /**
  26581. * Creates the VertexData of the Polyhedron.
  26582. */
  26583. VertexData.CreatePolyhedron = function (options) {
  26584. // provided polyhedron types :
  26585. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26586. // 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)
  26587. var polyhedra = [];
  26588. 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]] };
  26589. 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]] };
  26590. polyhedra[2] = {
  26591. 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]],
  26592. 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]]
  26593. };
  26594. polyhedra[3] = {
  26595. 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]],
  26596. 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]]
  26597. };
  26598. polyhedra[4] = {
  26599. 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]],
  26600. 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]]
  26601. };
  26602. 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]] };
  26603. 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]] };
  26604. 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]] };
  26605. 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]] };
  26606. 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]] };
  26607. 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]] };
  26608. 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]] };
  26609. 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]] };
  26610. 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]] };
  26611. polyhedra[14] = {
  26612. 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]],
  26613. 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]]
  26614. };
  26615. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26616. var size = options.size;
  26617. var sizeX = options.sizeX || size || 1;
  26618. var sizeY = options.sizeY || size || 1;
  26619. var sizeZ = options.sizeZ || size || 1;
  26620. var data = options.custom || polyhedra[type];
  26621. var nbfaces = data.face.length;
  26622. var faceUV = options.faceUV || new Array(nbfaces);
  26623. var faceColors = options.faceColors;
  26624. var flat = (options.flat === undefined) ? true : options.flat;
  26625. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26626. var positions = [];
  26627. var indices = [];
  26628. var normals = [];
  26629. var uvs = [];
  26630. var colors = [];
  26631. var index = 0;
  26632. var faceIdx = 0; // face cursor in the array "indexes"
  26633. var indexes = [];
  26634. var i = 0;
  26635. var f = 0;
  26636. var u, v, ang, x, y, tmp;
  26637. // default face colors and UV if undefined
  26638. if (flat) {
  26639. for (f = 0; f < nbfaces; f++) {
  26640. if (faceColors && faceColors[f] === undefined) {
  26641. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26642. }
  26643. if (faceUV && faceUV[f] === undefined) {
  26644. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26645. }
  26646. }
  26647. }
  26648. if (!flat) {
  26649. for (i = 0; i < data.vertex.length; i++) {
  26650. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26651. uvs.push(0, 0);
  26652. }
  26653. for (f = 0; f < nbfaces; f++) {
  26654. for (i = 0; i < data.face[f].length - 2; i++) {
  26655. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26656. }
  26657. }
  26658. }
  26659. else {
  26660. for (f = 0; f < nbfaces; f++) {
  26661. var fl = data.face[f].length; // number of vertices of the current face
  26662. ang = 2 * Math.PI / fl;
  26663. x = 0.5 * Math.tan(ang / 2);
  26664. y = 0.5;
  26665. // positions, uvs, colors
  26666. for (i = 0; i < fl; i++) {
  26667. // positions
  26668. 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);
  26669. indexes.push(index);
  26670. index++;
  26671. // uvs
  26672. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26673. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26674. uvs.push(u, v);
  26675. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26676. y = x * Math.sin(ang) + y * Math.cos(ang);
  26677. x = tmp;
  26678. // colors
  26679. if (faceColors) {
  26680. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26681. }
  26682. }
  26683. // indices from indexes
  26684. for (i = 0; i < fl - 2; i++) {
  26685. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26686. }
  26687. faceIdx += fl;
  26688. }
  26689. }
  26690. VertexData.ComputeNormals(positions, indices, normals);
  26691. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26692. var vertexData = new VertexData();
  26693. vertexData.positions = positions;
  26694. vertexData.indices = indices;
  26695. vertexData.normals = normals;
  26696. vertexData.uvs = uvs;
  26697. if (faceColors && flat) {
  26698. vertexData.colors = colors;
  26699. }
  26700. return vertexData;
  26701. };
  26702. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26703. /**
  26704. * Creates the VertexData of the Torus Knot.
  26705. */
  26706. VertexData.CreateTorusKnot = function (options) {
  26707. var indices = [];
  26708. var positions = [];
  26709. var normals = [];
  26710. var uvs = [];
  26711. var radius = options.radius || 2;
  26712. var tube = options.tube || 0.5;
  26713. var radialSegments = options.radialSegments || 32;
  26714. var tubularSegments = options.tubularSegments || 32;
  26715. var p = options.p || 2;
  26716. var q = options.q || 3;
  26717. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26718. // Helper
  26719. var getPos = function (angle) {
  26720. var cu = Math.cos(angle);
  26721. var su = Math.sin(angle);
  26722. var quOverP = q / p * angle;
  26723. var cs = Math.cos(quOverP);
  26724. var tx = radius * (2 + cs) * 0.5 * cu;
  26725. var ty = radius * (2 + cs) * su * 0.5;
  26726. var tz = radius * Math.sin(quOverP) * 0.5;
  26727. return new BABYLON.Vector3(tx, ty, tz);
  26728. };
  26729. // Vertices
  26730. var i;
  26731. var j;
  26732. for (i = 0; i <= radialSegments; i++) {
  26733. var modI = i % radialSegments;
  26734. var u = modI / radialSegments * 2 * p * Math.PI;
  26735. var p1 = getPos(u);
  26736. var p2 = getPos(u + 0.01);
  26737. var tang = p2.subtract(p1);
  26738. var n = p2.add(p1);
  26739. var bitan = BABYLON.Vector3.Cross(tang, n);
  26740. n = BABYLON.Vector3.Cross(bitan, tang);
  26741. bitan.normalize();
  26742. n.normalize();
  26743. for (j = 0; j < tubularSegments; j++) {
  26744. var modJ = j % tubularSegments;
  26745. var v = modJ / tubularSegments * 2 * Math.PI;
  26746. var cx = -tube * Math.cos(v);
  26747. var cy = tube * Math.sin(v);
  26748. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26749. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26750. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26751. uvs.push(i / radialSegments);
  26752. uvs.push(j / tubularSegments);
  26753. }
  26754. }
  26755. for (i = 0; i < radialSegments; i++) {
  26756. for (j = 0; j < tubularSegments; j++) {
  26757. var jNext = (j + 1) % tubularSegments;
  26758. var a = i * tubularSegments + j;
  26759. var b = (i + 1) * tubularSegments + j;
  26760. var c = (i + 1) * tubularSegments + jNext;
  26761. var d = i * tubularSegments + jNext;
  26762. indices.push(d);
  26763. indices.push(b);
  26764. indices.push(a);
  26765. indices.push(d);
  26766. indices.push(c);
  26767. indices.push(b);
  26768. }
  26769. }
  26770. // Normals
  26771. VertexData.ComputeNormals(positions, indices, normals);
  26772. // Sides
  26773. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26774. // Result
  26775. var vertexData = new VertexData();
  26776. vertexData.indices = indices;
  26777. vertexData.positions = positions;
  26778. vertexData.normals = normals;
  26779. vertexData.uvs = uvs;
  26780. return vertexData;
  26781. };
  26782. // Tools
  26783. /**
  26784. * @param {any} - positions (number[] or Float32Array)
  26785. * @param {any} - indices (number[] or Uint16Array)
  26786. * @param {any} - normals (number[] or Float32Array)
  26787. * options (optional) :
  26788. * facetPositions : optional array of facet positions (vector3)
  26789. * facetNormals : optional array of facet normals (vector3)
  26790. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26791. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26792. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26793. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26794. * bInfo : optional bounding info, required for facetPartitioning computation
  26795. */
  26796. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26797. // temporary scalar variables
  26798. var index = 0; // facet index
  26799. var p1p2x = 0.0; // p1p2 vector x coordinate
  26800. var p1p2y = 0.0; // p1p2 vector y coordinate
  26801. var p1p2z = 0.0; // p1p2 vector z coordinate
  26802. var p3p2x = 0.0; // p3p2 vector x coordinate
  26803. var p3p2y = 0.0; // p3p2 vector y coordinate
  26804. var p3p2z = 0.0; // p3p2 vector z coordinate
  26805. var faceNormalx = 0.0; // facet normal x coordinate
  26806. var faceNormaly = 0.0; // facet normal y coordinate
  26807. var faceNormalz = 0.0; // facet normal z coordinate
  26808. var length = 0.0; // facet normal length before normalization
  26809. var v1x = 0; // vector1 x index in the positions array
  26810. var v1y = 0; // vector1 y index in the positions array
  26811. var v1z = 0; // vector1 z index in the positions array
  26812. var v2x = 0; // vector2 x index in the positions array
  26813. var v2y = 0; // vector2 y index in the positions array
  26814. var v2z = 0; // vector2 z index in the positions array
  26815. var v3x = 0; // vector3 x index in the positions array
  26816. var v3y = 0; // vector3 y index in the positions array
  26817. var v3z = 0; // vector3 z index in the positions array
  26818. var computeFacetNormals = false;
  26819. var computeFacetPositions = false;
  26820. var computeFacetPartitioning = false;
  26821. var faceNormalSign = 1;
  26822. if (options) {
  26823. computeFacetNormals = (options.facetNormals) ? true : false;
  26824. computeFacetPositions = (options.facetPositions) ? true : false;
  26825. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26826. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26827. }
  26828. // facetPartitioning reinit if needed
  26829. if (computeFacetPartitioning) {
  26830. var ox = 0; // X partitioning index for facet position
  26831. var oy = 0; // Y partinioning index for facet position
  26832. var oz = 0; // Z partinioning index for facet position
  26833. var b1x = 0; // X partitioning index for facet v1 vertex
  26834. var b1y = 0; // Y partitioning index for facet v1 vertex
  26835. var b1z = 0; // z partitioning index for facet v1 vertex
  26836. var b2x = 0; // X partitioning index for facet v2 vertex
  26837. var b2y = 0; // Y partitioning index for facet v2 vertex
  26838. var b2z = 0; // Z partitioning index for facet v2 vertex
  26839. var b3x = 0; // X partitioning index for facet v3 vertex
  26840. var b3y = 0; // Y partitioning index for facet v3 vertex
  26841. var b3z = 0; // Z partitioning index for facet v3 vertex
  26842. var block_idx_o = 0; // facet barycenter block index
  26843. var block_idx_v1 = 0; // v1 vertex block index
  26844. var block_idx_v2 = 0; // v2 vertex block index
  26845. var block_idx_v3 = 0; // v3 vertex block index
  26846. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26847. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26848. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26849. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26850. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26851. var subSq = options.subDiv.max * options.subDiv.max;
  26852. options.facetPartitioning.length = 0;
  26853. }
  26854. // reset the normals
  26855. for (index = 0; index < positions.length; index++) {
  26856. normals[index] = 0.0;
  26857. }
  26858. // Loop : 1 indice triplet = 1 facet
  26859. var nbFaces = indices.length / 3;
  26860. for (index = 0; index < nbFaces; index++) {
  26861. // get the indexes of the coordinates of each vertex of the facet
  26862. v1x = indices[index * 3] * 3;
  26863. v1y = v1x + 1;
  26864. v1z = v1x + 2;
  26865. v2x = indices[index * 3 + 1] * 3;
  26866. v2y = v2x + 1;
  26867. v2z = v2x + 2;
  26868. v3x = indices[index * 3 + 2] * 3;
  26869. v3y = v3x + 1;
  26870. v3z = v3x + 2;
  26871. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26872. p1p2y = positions[v1y] - positions[v2y];
  26873. p1p2z = positions[v1z] - positions[v2z];
  26874. p3p2x = positions[v3x] - positions[v2x];
  26875. p3p2y = positions[v3y] - positions[v2y];
  26876. p3p2z = positions[v3z] - positions[v2z];
  26877. // compute the face normal with the cross product
  26878. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26879. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26880. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26881. // normalize this normal and store it in the array facetData
  26882. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26883. length = (length === 0) ? 1.0 : length;
  26884. faceNormalx /= length;
  26885. faceNormaly /= length;
  26886. faceNormalz /= length;
  26887. if (computeFacetNormals) {
  26888. options.facetNormals[index].x = faceNormalx;
  26889. options.facetNormals[index].y = faceNormaly;
  26890. options.facetNormals[index].z = faceNormalz;
  26891. }
  26892. if (computeFacetPositions) {
  26893. // compute and the facet barycenter coordinates in the array facetPositions
  26894. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26895. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26896. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26897. }
  26898. if (computeFacetPartitioning) {
  26899. // store the facet indexes in arrays in the main facetPartitioning array :
  26900. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26901. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26902. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26903. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26904. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26905. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26906. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26907. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26908. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26909. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26910. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26911. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26912. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26913. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26914. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26915. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26916. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26917. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26918. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26919. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26920. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26921. // push each facet index in each block containing the vertex
  26922. options.facetPartitioning[block_idx_v1].push(index);
  26923. if (block_idx_v2 != block_idx_v1) {
  26924. options.facetPartitioning[block_idx_v2].push(index);
  26925. }
  26926. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26927. options.facetPartitioning[block_idx_v3].push(index);
  26928. }
  26929. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26930. options.facetPartitioning[block_idx_o].push(index);
  26931. }
  26932. }
  26933. // compute the normals anyway
  26934. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26935. normals[v1y] += faceNormaly;
  26936. normals[v1z] += faceNormalz;
  26937. normals[v2x] += faceNormalx;
  26938. normals[v2y] += faceNormaly;
  26939. normals[v2z] += faceNormalz;
  26940. normals[v3x] += faceNormalx;
  26941. normals[v3y] += faceNormaly;
  26942. normals[v3z] += faceNormalz;
  26943. }
  26944. // last normalization of each normal
  26945. for (index = 0; index < normals.length / 3; index++) {
  26946. faceNormalx = normals[index * 3];
  26947. faceNormaly = normals[index * 3 + 1];
  26948. faceNormalz = normals[index * 3 + 2];
  26949. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26950. length = (length === 0) ? 1.0 : length;
  26951. faceNormalx /= length;
  26952. faceNormaly /= length;
  26953. faceNormalz /= length;
  26954. normals[index * 3] = faceNormalx;
  26955. normals[index * 3 + 1] = faceNormaly;
  26956. normals[index * 3 + 2] = faceNormalz;
  26957. }
  26958. };
  26959. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26960. var li = indices.length;
  26961. var ln = normals.length;
  26962. var i;
  26963. var n;
  26964. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26965. switch (sideOrientation) {
  26966. case BABYLON.Mesh.FRONTSIDE:
  26967. // nothing changed
  26968. break;
  26969. case BABYLON.Mesh.BACKSIDE:
  26970. var tmp;
  26971. // indices
  26972. for (i = 0; i < li; i += 3) {
  26973. tmp = indices[i];
  26974. indices[i] = indices[i + 2];
  26975. indices[i + 2] = tmp;
  26976. }
  26977. // normals
  26978. for (n = 0; n < ln; n++) {
  26979. normals[n] = -normals[n];
  26980. }
  26981. break;
  26982. case BABYLON.Mesh.DOUBLESIDE:
  26983. // positions
  26984. var lp = positions.length;
  26985. var l = lp / 3;
  26986. for (var p = 0; p < lp; p++) {
  26987. positions[lp + p] = positions[p];
  26988. }
  26989. // indices
  26990. for (i = 0; i < li; i += 3) {
  26991. indices[i + li] = indices[i + 2] + l;
  26992. indices[i + 1 + li] = indices[i + 1] + l;
  26993. indices[i + 2 + li] = indices[i] + l;
  26994. }
  26995. // normals
  26996. for (n = 0; n < ln; n++) {
  26997. normals[ln + n] = -normals[n];
  26998. }
  26999. // uvs
  27000. var lu = uvs.length;
  27001. var u = 0;
  27002. for (u = 0; u < lu; u++) {
  27003. uvs[u + lu] = uvs[u];
  27004. }
  27005. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27006. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27007. u = 0;
  27008. for (i = 0; i < lu / 2; i++) {
  27009. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27010. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27011. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27012. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27013. u += 2;
  27014. }
  27015. break;
  27016. }
  27017. };
  27018. /**
  27019. * Creates a new VertexData from the imported parameters.
  27020. */
  27021. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27022. var vertexData = new VertexData();
  27023. // positions
  27024. var positions = parsedVertexData.positions;
  27025. if (positions) {
  27026. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27027. }
  27028. // normals
  27029. var normals = parsedVertexData.normals;
  27030. if (normals) {
  27031. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27032. }
  27033. // tangents
  27034. var tangents = parsedVertexData.tangents;
  27035. if (tangents) {
  27036. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27037. }
  27038. // uvs
  27039. var uvs = parsedVertexData.uvs;
  27040. if (uvs) {
  27041. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27042. }
  27043. // uv2s
  27044. var uv2s = parsedVertexData.uv2s;
  27045. if (uv2s) {
  27046. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27047. }
  27048. // uv3s
  27049. var uv3s = parsedVertexData.uv3s;
  27050. if (uv3s) {
  27051. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27052. }
  27053. // uv4s
  27054. var uv4s = parsedVertexData.uv4s;
  27055. if (uv4s) {
  27056. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27057. }
  27058. // uv5s
  27059. var uv5s = parsedVertexData.uv5s;
  27060. if (uv5s) {
  27061. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27062. }
  27063. // uv6s
  27064. var uv6s = parsedVertexData.uv6s;
  27065. if (uv6s) {
  27066. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27067. }
  27068. // colors
  27069. var colors = parsedVertexData.colors;
  27070. if (colors) {
  27071. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27072. }
  27073. // matricesIndices
  27074. var matricesIndices = parsedVertexData.matricesIndices;
  27075. if (matricesIndices) {
  27076. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27077. }
  27078. // matricesWeights
  27079. var matricesWeights = parsedVertexData.matricesWeights;
  27080. if (matricesWeights) {
  27081. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27082. }
  27083. // indices
  27084. var indices = parsedVertexData.indices;
  27085. if (indices) {
  27086. vertexData.indices = indices;
  27087. }
  27088. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27089. };
  27090. return VertexData;
  27091. }());
  27092. BABYLON.VertexData = VertexData;
  27093. })(BABYLON || (BABYLON = {}));
  27094. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27095. var BABYLON;
  27096. (function (BABYLON) {
  27097. var Geometry = (function () {
  27098. function Geometry(id, scene, vertexData, updatable, mesh) {
  27099. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27100. this._totalVertices = 0;
  27101. this._isDisposed = false;
  27102. this.id = id;
  27103. this._engine = scene.getEngine();
  27104. this._meshes = [];
  27105. this._scene = scene;
  27106. //Init vertex buffer cache
  27107. this._vertexBuffers = {};
  27108. this._indices = [];
  27109. // vertexData
  27110. if (vertexData) {
  27111. this.setAllVerticesData(vertexData, updatable);
  27112. }
  27113. else {
  27114. this._totalVertices = 0;
  27115. this._indices = [];
  27116. }
  27117. if (this._engine.getCaps().vertexArrayObject) {
  27118. this._vertexArrayObjects = {};
  27119. }
  27120. // applyToMesh
  27121. if (mesh) {
  27122. if (mesh.getClassName() === "LinesMesh") {
  27123. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27124. this.updateExtend();
  27125. }
  27126. this.applyToMesh(mesh);
  27127. mesh.computeWorldMatrix(true);
  27128. }
  27129. }
  27130. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27131. /**
  27132. * 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
  27133. * @returns The Bias Vector
  27134. */
  27135. get: function () {
  27136. return this._boundingBias;
  27137. },
  27138. set: function (value) {
  27139. if (this._boundingBias && this._boundingBias.equals(value)) {
  27140. return;
  27141. }
  27142. this._boundingBias = value.clone();
  27143. this.updateBoundingInfo(true, null);
  27144. },
  27145. enumerable: true,
  27146. configurable: true
  27147. });
  27148. Object.defineProperty(Geometry.prototype, "extend", {
  27149. get: function () {
  27150. return this._extend;
  27151. },
  27152. enumerable: true,
  27153. configurable: true
  27154. });
  27155. Geometry.prototype.getScene = function () {
  27156. return this._scene;
  27157. };
  27158. Geometry.prototype.getEngine = function () {
  27159. return this._engine;
  27160. };
  27161. Geometry.prototype.isReady = function () {
  27162. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27163. };
  27164. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27165. get: function () {
  27166. for (var index = 0; index < this._meshes.length; index++) {
  27167. if (!this._meshes[index].doNotSerialize) {
  27168. return false;
  27169. }
  27170. }
  27171. return true;
  27172. },
  27173. enumerable: true,
  27174. configurable: true
  27175. });
  27176. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27177. vertexData.applyToGeometry(this, updatable);
  27178. this.notifyUpdate();
  27179. };
  27180. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27181. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27182. this.setVerticesBuffer(buffer);
  27183. };
  27184. Geometry.prototype.removeVerticesData = function (kind) {
  27185. if (this._vertexBuffers[kind]) {
  27186. this._vertexBuffers[kind].dispose();
  27187. delete this._vertexBuffers[kind];
  27188. }
  27189. };
  27190. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27191. var kind = buffer.getKind();
  27192. if (this._vertexBuffers[kind]) {
  27193. this._vertexBuffers[kind].dispose();
  27194. }
  27195. this._vertexBuffers[kind] = buffer;
  27196. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27197. var data = buffer.getData();
  27198. var stride = buffer.getStrideSize();
  27199. this._totalVertices = data.length / stride;
  27200. this.updateExtend(data, stride);
  27201. this._resetPointsArrayCache();
  27202. var meshes = this._meshes;
  27203. var numOfMeshes = meshes.length;
  27204. for (var index = 0; index < numOfMeshes; index++) {
  27205. var mesh = meshes[index];
  27206. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27207. mesh._createGlobalSubMesh();
  27208. mesh.computeWorldMatrix(true);
  27209. }
  27210. }
  27211. this.notifyUpdate(kind);
  27212. if (this._vertexArrayObjects) {
  27213. this._disposeVertexArrayObjects();
  27214. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27215. }
  27216. };
  27217. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27218. var vertexBuffer = this.getVertexBuffer(kind);
  27219. if (!vertexBuffer) {
  27220. return;
  27221. }
  27222. vertexBuffer.updateDirectly(data, offset);
  27223. this.notifyUpdate(kind);
  27224. };
  27225. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27226. var vertexBuffer = this.getVertexBuffer(kind);
  27227. if (!vertexBuffer) {
  27228. return;
  27229. }
  27230. vertexBuffer.update(data);
  27231. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27232. var stride = vertexBuffer.getStrideSize();
  27233. this._totalVertices = data.length / stride;
  27234. this.updateBoundingInfo(updateExtends, data);
  27235. }
  27236. this.notifyUpdate(kind);
  27237. };
  27238. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27239. if (updateExtends) {
  27240. this.updateExtend(data);
  27241. }
  27242. var meshes = this._meshes;
  27243. var numOfMeshes = meshes.length;
  27244. this._resetPointsArrayCache();
  27245. for (var index = 0; index < numOfMeshes; index++) {
  27246. var mesh = meshes[index];
  27247. if (updateExtends) {
  27248. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27249. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27250. var subMesh = mesh.subMeshes[subIndex];
  27251. subMesh.refreshBoundingInfo();
  27252. }
  27253. }
  27254. }
  27255. };
  27256. Geometry.prototype._bind = function (effect, indexToBind) {
  27257. if (indexToBind === void 0) { indexToBind = undefined; }
  27258. if (indexToBind === undefined) {
  27259. indexToBind = this._indexBuffer;
  27260. }
  27261. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27262. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27263. return;
  27264. }
  27265. // Using VAO
  27266. if (!this._vertexArrayObjects[effect.key]) {
  27267. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27268. }
  27269. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27270. };
  27271. Geometry.prototype.getTotalVertices = function () {
  27272. if (!this.isReady()) {
  27273. return 0;
  27274. }
  27275. return this._totalVertices;
  27276. };
  27277. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27278. var vertexBuffer = this.getVertexBuffer(kind);
  27279. if (!vertexBuffer) {
  27280. return null;
  27281. }
  27282. var orig = vertexBuffer.getData();
  27283. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27284. return orig;
  27285. }
  27286. else {
  27287. var len = orig.length;
  27288. var copy = [];
  27289. for (var i = 0; i < len; i++) {
  27290. copy.push(orig[i]);
  27291. }
  27292. return copy;
  27293. }
  27294. };
  27295. Geometry.prototype.getVertexBuffer = function (kind) {
  27296. if (!this.isReady()) {
  27297. return null;
  27298. }
  27299. return this._vertexBuffers[kind];
  27300. };
  27301. Geometry.prototype.getVertexBuffers = function () {
  27302. if (!this.isReady()) {
  27303. return null;
  27304. }
  27305. return this._vertexBuffers;
  27306. };
  27307. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27308. if (!this._vertexBuffers) {
  27309. if (this._delayInfo) {
  27310. return this._delayInfo.indexOf(kind) !== -1;
  27311. }
  27312. return false;
  27313. }
  27314. return this._vertexBuffers[kind] !== undefined;
  27315. };
  27316. Geometry.prototype.getVerticesDataKinds = function () {
  27317. var result = [];
  27318. var kind;
  27319. if (!this._vertexBuffers && this._delayInfo) {
  27320. for (kind in this._delayInfo) {
  27321. result.push(kind);
  27322. }
  27323. }
  27324. else {
  27325. for (kind in this._vertexBuffers) {
  27326. result.push(kind);
  27327. }
  27328. }
  27329. return result;
  27330. };
  27331. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27332. if (this._indexBuffer) {
  27333. this._engine._releaseBuffer(this._indexBuffer);
  27334. }
  27335. this._disposeVertexArrayObjects();
  27336. this._indices = indices;
  27337. if (this._meshes.length !== 0 && this._indices) {
  27338. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27339. }
  27340. if (totalVertices !== undefined) {
  27341. this._totalVertices = totalVertices;
  27342. }
  27343. var meshes = this._meshes;
  27344. var numOfMeshes = meshes.length;
  27345. for (var index = 0; index < numOfMeshes; index++) {
  27346. meshes[index]._createGlobalSubMesh();
  27347. }
  27348. this.notifyUpdate();
  27349. };
  27350. Geometry.prototype.getTotalIndices = function () {
  27351. if (!this.isReady()) {
  27352. return 0;
  27353. }
  27354. return this._indices.length;
  27355. };
  27356. Geometry.prototype.getIndices = function (copyWhenShared) {
  27357. if (!this.isReady()) {
  27358. return null;
  27359. }
  27360. var orig = this._indices;
  27361. if (!copyWhenShared || this._meshes.length === 1) {
  27362. return orig;
  27363. }
  27364. else {
  27365. var len = orig.length;
  27366. var copy = [];
  27367. for (var i = 0; i < len; i++) {
  27368. copy.push(orig[i]);
  27369. }
  27370. return copy;
  27371. }
  27372. };
  27373. Geometry.prototype.getIndexBuffer = function () {
  27374. if (!this.isReady()) {
  27375. return null;
  27376. }
  27377. return this._indexBuffer;
  27378. };
  27379. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27380. if (!effect || !this._vertexArrayObjects) {
  27381. return;
  27382. }
  27383. if (this._vertexArrayObjects[effect.key]) {
  27384. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27385. delete this._vertexArrayObjects[effect.key];
  27386. }
  27387. };
  27388. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27389. var meshes = this._meshes;
  27390. var index = meshes.indexOf(mesh);
  27391. if (index === -1) {
  27392. return;
  27393. }
  27394. meshes.splice(index, 1);
  27395. mesh._geometry = null;
  27396. if (meshes.length === 0 && shouldDispose) {
  27397. this.dispose();
  27398. }
  27399. };
  27400. Geometry.prototype.applyToMesh = function (mesh) {
  27401. if (mesh._geometry === this) {
  27402. return;
  27403. }
  27404. var previousGeometry = mesh._geometry;
  27405. if (previousGeometry) {
  27406. previousGeometry.releaseForMesh(mesh);
  27407. }
  27408. var meshes = this._meshes;
  27409. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27410. mesh._geometry = this;
  27411. this._scene.pushGeometry(this);
  27412. meshes.push(mesh);
  27413. if (this.isReady()) {
  27414. this._applyToMesh(mesh);
  27415. }
  27416. else {
  27417. mesh._boundingInfo = this._boundingInfo;
  27418. }
  27419. };
  27420. Geometry.prototype.updateExtend = function (data, stride) {
  27421. if (data === void 0) { data = null; }
  27422. if (!data) {
  27423. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27424. }
  27425. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27426. };
  27427. Geometry.prototype._applyToMesh = function (mesh) {
  27428. var numOfMeshes = this._meshes.length;
  27429. // vertexBuffers
  27430. for (var kind in this._vertexBuffers) {
  27431. if (numOfMeshes === 1) {
  27432. this._vertexBuffers[kind].create();
  27433. }
  27434. var buffer = this._vertexBuffers[kind].getBuffer();
  27435. if (buffer)
  27436. buffer.references = numOfMeshes;
  27437. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27438. if (!this._extend) {
  27439. this.updateExtend(this._vertexBuffers[kind].getData());
  27440. }
  27441. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27442. mesh._createGlobalSubMesh();
  27443. //bounding info was just created again, world matrix should be applied again.
  27444. mesh._updateBoundingInfo();
  27445. }
  27446. }
  27447. // indexBuffer
  27448. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27449. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27450. }
  27451. if (this._indexBuffer) {
  27452. this._indexBuffer.references = numOfMeshes;
  27453. }
  27454. };
  27455. Geometry.prototype.notifyUpdate = function (kind) {
  27456. if (this.onGeometryUpdated) {
  27457. this.onGeometryUpdated(this, kind);
  27458. }
  27459. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27460. var mesh = _a[_i];
  27461. mesh._markSubMeshesAsAttributesDirty();
  27462. }
  27463. };
  27464. Geometry.prototype.load = function (scene, onLoaded) {
  27465. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27466. return;
  27467. }
  27468. if (this.isReady()) {
  27469. if (onLoaded) {
  27470. onLoaded();
  27471. }
  27472. return;
  27473. }
  27474. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27475. this._queueLoad(scene, onLoaded);
  27476. };
  27477. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27478. var _this = this;
  27479. scene._addPendingData(this);
  27480. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27481. _this._delayLoadingFunction(JSON.parse(data), _this);
  27482. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27483. _this._delayInfo = [];
  27484. scene._removePendingData(_this);
  27485. var meshes = _this._meshes;
  27486. var numOfMeshes = meshes.length;
  27487. for (var index = 0; index < numOfMeshes; index++) {
  27488. _this._applyToMesh(meshes[index]);
  27489. }
  27490. if (onLoaded) {
  27491. onLoaded();
  27492. }
  27493. }, function () { }, scene.database);
  27494. };
  27495. /**
  27496. * Invert the geometry to move from a right handed system to a left handed one.
  27497. */
  27498. Geometry.prototype.toLeftHanded = function () {
  27499. // Flip faces
  27500. var tIndices = this.getIndices(false);
  27501. if (tIndices != null && tIndices.length > 0) {
  27502. for (var i = 0; i < tIndices.length; i += 3) {
  27503. var tTemp = tIndices[i + 0];
  27504. tIndices[i + 0] = tIndices[i + 2];
  27505. tIndices[i + 2] = tTemp;
  27506. }
  27507. this.setIndices(tIndices);
  27508. }
  27509. // Negate position.z
  27510. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27511. if (tPositions != null && tPositions.length > 0) {
  27512. for (var i = 0; i < tPositions.length; i += 3) {
  27513. tPositions[i + 2] = -tPositions[i + 2];
  27514. }
  27515. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27516. }
  27517. // Negate normal.z
  27518. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27519. if (tNormals != null && tNormals.length > 0) {
  27520. for (var i = 0; i < tNormals.length; i += 3) {
  27521. tNormals[i + 2] = -tNormals[i + 2];
  27522. }
  27523. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27524. }
  27525. };
  27526. // Cache
  27527. Geometry.prototype._resetPointsArrayCache = function () {
  27528. this._positions = null;
  27529. };
  27530. Geometry.prototype._generatePointsArray = function () {
  27531. if (this._positions)
  27532. return true;
  27533. this._positions = [];
  27534. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27535. if (!data) {
  27536. return false;
  27537. }
  27538. for (var index = 0; index < data.length; index += 3) {
  27539. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27540. }
  27541. return true;
  27542. };
  27543. Geometry.prototype.isDisposed = function () {
  27544. return this._isDisposed;
  27545. };
  27546. Geometry.prototype._disposeVertexArrayObjects = function () {
  27547. if (this._vertexArrayObjects) {
  27548. for (var kind in this._vertexArrayObjects) {
  27549. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27550. }
  27551. this._vertexArrayObjects = {};
  27552. }
  27553. };
  27554. Geometry.prototype.dispose = function () {
  27555. var meshes = this._meshes;
  27556. var numOfMeshes = meshes.length;
  27557. var index;
  27558. for (index = 0; index < numOfMeshes; index++) {
  27559. this.releaseForMesh(meshes[index]);
  27560. }
  27561. this._meshes = [];
  27562. this._disposeVertexArrayObjects();
  27563. for (var kind in this._vertexBuffers) {
  27564. this._vertexBuffers[kind].dispose();
  27565. }
  27566. this._vertexBuffers = {};
  27567. this._totalVertices = 0;
  27568. if (this._indexBuffer) {
  27569. this._engine._releaseBuffer(this._indexBuffer);
  27570. }
  27571. this._indexBuffer = null;
  27572. this._indices = [];
  27573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27574. this.delayLoadingFile = null;
  27575. this._delayLoadingFunction = null;
  27576. this._delayInfo = [];
  27577. this._boundingInfo = null;
  27578. this._scene.removeGeometry(this);
  27579. this._isDisposed = true;
  27580. };
  27581. Geometry.prototype.copy = function (id) {
  27582. var vertexData = new BABYLON.VertexData();
  27583. vertexData.indices = [];
  27584. var indices = this.getIndices();
  27585. for (var index = 0; index < indices.length; index++) {
  27586. vertexData.indices.push(indices[index]);
  27587. }
  27588. var updatable = false;
  27589. var stopChecking = false;
  27590. var kind;
  27591. for (kind in this._vertexBuffers) {
  27592. // using slice() to make a copy of the array and not just reference it
  27593. var data = this.getVerticesData(kind);
  27594. if (data instanceof Float32Array) {
  27595. vertexData.set(new Float32Array(data), kind);
  27596. }
  27597. else {
  27598. vertexData.set(data.slice(0), kind);
  27599. }
  27600. if (!stopChecking) {
  27601. updatable = this.getVertexBuffer(kind).isUpdatable();
  27602. stopChecking = !updatable;
  27603. }
  27604. }
  27605. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27606. geometry.delayLoadState = this.delayLoadState;
  27607. geometry.delayLoadingFile = this.delayLoadingFile;
  27608. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27609. for (kind in this._delayInfo) {
  27610. geometry._delayInfo = geometry._delayInfo || [];
  27611. geometry._delayInfo.push(kind);
  27612. }
  27613. // Bounding info
  27614. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27615. return geometry;
  27616. };
  27617. Geometry.prototype.serialize = function () {
  27618. var serializationObject = {};
  27619. serializationObject.id = this.id;
  27620. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27621. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27622. }
  27623. return serializationObject;
  27624. };
  27625. Geometry.prototype.toNumberArray = function (origin) {
  27626. if (Array.isArray(origin)) {
  27627. return origin;
  27628. }
  27629. else {
  27630. return Array.prototype.slice.call(origin);
  27631. }
  27632. };
  27633. Geometry.prototype.serializeVerticeData = function () {
  27634. var serializationObject = this.serialize();
  27635. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27636. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27637. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27638. serializationObject.positions._updatable = true;
  27639. }
  27640. }
  27641. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27642. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27643. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27644. serializationObject.normals._updatable = true;
  27645. }
  27646. }
  27647. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27648. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27649. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27650. serializationObject.uvs._updatable = true;
  27651. }
  27652. }
  27653. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27654. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27655. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27656. serializationObject.uv2s._updatable = true;
  27657. }
  27658. }
  27659. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27660. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27661. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27662. serializationObject.uv3s._updatable = true;
  27663. }
  27664. }
  27665. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27666. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27667. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27668. serializationObject.uv4s._updatable = true;
  27669. }
  27670. }
  27671. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27672. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27673. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27674. serializationObject.uv5s._updatable = true;
  27675. }
  27676. }
  27677. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27678. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27679. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27680. serializationObject.uv6s._updatable = true;
  27681. }
  27682. }
  27683. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27684. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27685. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27686. serializationObject.colors._updatable = true;
  27687. }
  27688. }
  27689. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27690. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27691. serializationObject.matricesIndices._isExpanded = true;
  27692. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27693. serializationObject.matricesIndices._updatable = true;
  27694. }
  27695. }
  27696. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27697. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27698. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27699. serializationObject.matricesWeights._updatable = true;
  27700. }
  27701. }
  27702. serializationObject.indices = this.toNumberArray(this.getIndices());
  27703. return serializationObject;
  27704. };
  27705. // Statics
  27706. Geometry.ExtractFromMesh = function (mesh, id) {
  27707. var geometry = mesh._geometry;
  27708. if (!geometry) {
  27709. return null;
  27710. }
  27711. return geometry.copy(id);
  27712. };
  27713. /**
  27714. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27715. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27716. * Be aware Math.random() could cause collisions, but:
  27717. * "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"
  27718. */
  27719. Geometry.RandomId = function () {
  27720. return BABYLON.Tools.RandomId();
  27721. };
  27722. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27723. var scene = mesh.getScene();
  27724. // Geometry
  27725. var geometryId = parsedGeometry.geometryId;
  27726. if (geometryId) {
  27727. var geometry = scene.getGeometryByID(geometryId);
  27728. if (geometry) {
  27729. geometry.applyToMesh(mesh);
  27730. }
  27731. }
  27732. else if (parsedGeometry instanceof ArrayBuffer) {
  27733. var binaryInfo = mesh._binaryInfo;
  27734. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27735. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27736. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27737. }
  27738. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27739. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27740. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27741. }
  27742. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27743. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27744. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27745. }
  27746. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27747. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27748. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27749. }
  27750. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27751. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27752. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27753. }
  27754. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27755. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27756. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27757. }
  27758. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27759. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27760. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27761. }
  27762. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27763. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27764. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27765. }
  27766. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27767. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27768. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27769. }
  27770. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27771. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27772. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27773. }
  27774. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27775. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27776. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27777. }
  27778. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27779. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27780. mesh.setIndices(indicesData);
  27781. }
  27782. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27783. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27784. mesh.subMeshes = [];
  27785. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27786. var materialIndex = subMeshesData[(i * 5) + 0];
  27787. var verticesStart = subMeshesData[(i * 5) + 1];
  27788. var verticesCount = subMeshesData[(i * 5) + 2];
  27789. var indexStart = subMeshesData[(i * 5) + 3];
  27790. var indexCount = subMeshesData[(i * 5) + 4];
  27791. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27792. }
  27793. }
  27794. }
  27795. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27796. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27797. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27798. if (parsedGeometry.uvs) {
  27799. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27800. }
  27801. if (parsedGeometry.uvs2) {
  27802. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27803. }
  27804. if (parsedGeometry.uvs3) {
  27805. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27806. }
  27807. if (parsedGeometry.uvs4) {
  27808. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27809. }
  27810. if (parsedGeometry.uvs5) {
  27811. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27812. }
  27813. if (parsedGeometry.uvs6) {
  27814. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27815. }
  27816. if (parsedGeometry.colors) {
  27817. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27818. }
  27819. if (parsedGeometry.matricesIndices) {
  27820. if (!parsedGeometry.matricesIndices._isExpanded) {
  27821. var floatIndices = [];
  27822. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27823. var matricesIndex = parsedGeometry.matricesIndices[i];
  27824. floatIndices.push(matricesIndex & 0x000000FF);
  27825. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27826. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27827. floatIndices.push(matricesIndex >> 24);
  27828. }
  27829. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27830. }
  27831. else {
  27832. delete parsedGeometry.matricesIndices._isExpanded;
  27833. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27834. }
  27835. }
  27836. if (parsedGeometry.matricesIndicesExtra) {
  27837. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27838. var floatIndices = [];
  27839. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27840. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27841. floatIndices.push(matricesIndex & 0x000000FF);
  27842. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27843. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27844. floatIndices.push(matricesIndex >> 24);
  27845. }
  27846. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27847. }
  27848. else {
  27849. delete parsedGeometry.matricesIndices._isExpanded;
  27850. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27851. }
  27852. }
  27853. if (parsedGeometry.matricesWeights) {
  27854. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27855. }
  27856. if (parsedGeometry.matricesWeightsExtra) {
  27857. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27858. }
  27859. mesh.setIndices(parsedGeometry.indices);
  27860. }
  27861. // SubMeshes
  27862. if (parsedGeometry.subMeshes) {
  27863. mesh.subMeshes = [];
  27864. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27865. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27866. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27867. }
  27868. }
  27869. // Flat shading
  27870. if (mesh._shouldGenerateFlatShading) {
  27871. mesh.convertToFlatShadedMesh();
  27872. delete mesh._shouldGenerateFlatShading;
  27873. }
  27874. // Update
  27875. mesh.computeWorldMatrix(true);
  27876. // Octree
  27877. if (scene['_selectionOctree']) {
  27878. scene['_selectionOctree'].addMesh(mesh);
  27879. }
  27880. };
  27881. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27882. if (scene.getGeometryByID(parsedVertexData.id)) {
  27883. return null; // null since geometry could be something else than a box...
  27884. }
  27885. var geometry = new Geometry(parsedVertexData.id, scene);
  27886. if (BABYLON.Tags) {
  27887. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27888. }
  27889. if (parsedVertexData.delayLoadingFile) {
  27890. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27891. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27892. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27893. geometry._delayInfo = [];
  27894. if (parsedVertexData.hasUVs) {
  27895. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27896. }
  27897. if (parsedVertexData.hasUVs2) {
  27898. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27899. }
  27900. if (parsedVertexData.hasUVs3) {
  27901. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27902. }
  27903. if (parsedVertexData.hasUVs4) {
  27904. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27905. }
  27906. if (parsedVertexData.hasUVs5) {
  27907. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27908. }
  27909. if (parsedVertexData.hasUVs6) {
  27910. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27911. }
  27912. if (parsedVertexData.hasColors) {
  27913. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27914. }
  27915. if (parsedVertexData.hasMatricesIndices) {
  27916. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27917. }
  27918. if (parsedVertexData.hasMatricesWeights) {
  27919. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27920. }
  27921. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27922. }
  27923. else {
  27924. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27925. }
  27926. scene.pushGeometry(geometry, true);
  27927. return geometry;
  27928. };
  27929. return Geometry;
  27930. }());
  27931. BABYLON.Geometry = Geometry;
  27932. /////// Primitives //////////////////////////////////////////////
  27933. (function (Geometry) {
  27934. var Primitives;
  27935. (function (Primitives) {
  27936. /// Abstract class
  27937. var _Primitive = (function (_super) {
  27938. __extends(_Primitive, _super);
  27939. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27940. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27941. _this._canBeRegenerated = _canBeRegenerated;
  27942. _this._beingRegenerated = true;
  27943. _this.regenerate();
  27944. _this._beingRegenerated = false;
  27945. return _this;
  27946. }
  27947. _Primitive.prototype.canBeRegenerated = function () {
  27948. return this._canBeRegenerated;
  27949. };
  27950. _Primitive.prototype.regenerate = function () {
  27951. if (!this._canBeRegenerated) {
  27952. return;
  27953. }
  27954. this._beingRegenerated = true;
  27955. this.setAllVerticesData(this._regenerateVertexData(), false);
  27956. this._beingRegenerated = false;
  27957. };
  27958. _Primitive.prototype.asNewGeometry = function (id) {
  27959. return _super.prototype.copy.call(this, id);
  27960. };
  27961. // overrides
  27962. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27963. if (!this._beingRegenerated) {
  27964. return;
  27965. }
  27966. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27967. };
  27968. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27969. if (!this._beingRegenerated) {
  27970. return;
  27971. }
  27972. _super.prototype.setVerticesData.call(this, kind, data, false);
  27973. };
  27974. // to override
  27975. // protected
  27976. _Primitive.prototype._regenerateVertexData = function () {
  27977. throw new Error("Abstract method");
  27978. };
  27979. _Primitive.prototype.copy = function (id) {
  27980. throw new Error("Must be overriden in sub-classes.");
  27981. };
  27982. _Primitive.prototype.serialize = function () {
  27983. var serializationObject = _super.prototype.serialize.call(this);
  27984. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27985. return serializationObject;
  27986. };
  27987. return _Primitive;
  27988. }(Geometry));
  27989. Primitives._Primitive = _Primitive;
  27990. var Ribbon = (function (_super) {
  27991. __extends(Ribbon, _super);
  27992. // Members
  27993. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27994. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27995. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27996. _this.pathArray = pathArray;
  27997. _this.closeArray = closeArray;
  27998. _this.closePath = closePath;
  27999. _this.offset = offset;
  28000. _this.side = side;
  28001. return _this;
  28002. }
  28003. Ribbon.prototype._regenerateVertexData = function () {
  28004. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28005. };
  28006. Ribbon.prototype.copy = function (id) {
  28007. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28008. };
  28009. return Ribbon;
  28010. }(_Primitive));
  28011. Primitives.Ribbon = Ribbon;
  28012. var Box = (function (_super) {
  28013. __extends(Box, _super);
  28014. // Members
  28015. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28016. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28017. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28018. _this.size = size;
  28019. _this.side = side;
  28020. return _this;
  28021. }
  28022. Box.prototype._regenerateVertexData = function () {
  28023. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28024. };
  28025. Box.prototype.copy = function (id) {
  28026. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28027. };
  28028. Box.prototype.serialize = function () {
  28029. var serializationObject = _super.prototype.serialize.call(this);
  28030. serializationObject.size = this.size;
  28031. return serializationObject;
  28032. };
  28033. Box.Parse = function (parsedBox, scene) {
  28034. if (scene.getGeometryByID(parsedBox.id)) {
  28035. return null; // null since geometry could be something else than a box...
  28036. }
  28037. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28038. if (BABYLON.Tags) {
  28039. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28040. }
  28041. scene.pushGeometry(box, true);
  28042. return box;
  28043. };
  28044. return Box;
  28045. }(_Primitive));
  28046. Primitives.Box = Box;
  28047. var Sphere = (function (_super) {
  28048. __extends(Sphere, _super);
  28049. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28050. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28051. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28052. _this.segments = segments;
  28053. _this.diameter = diameter;
  28054. _this.side = side;
  28055. return _this;
  28056. }
  28057. Sphere.prototype._regenerateVertexData = function () {
  28058. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28059. };
  28060. Sphere.prototype.copy = function (id) {
  28061. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28062. };
  28063. Sphere.prototype.serialize = function () {
  28064. var serializationObject = _super.prototype.serialize.call(this);
  28065. serializationObject.segments = this.segments;
  28066. serializationObject.diameter = this.diameter;
  28067. return serializationObject;
  28068. };
  28069. Sphere.Parse = function (parsedSphere, scene) {
  28070. if (scene.getGeometryByID(parsedSphere.id)) {
  28071. return null; // null since geometry could be something else than a sphere...
  28072. }
  28073. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28074. if (BABYLON.Tags) {
  28075. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28076. }
  28077. scene.pushGeometry(sphere, true);
  28078. return sphere;
  28079. };
  28080. return Sphere;
  28081. }(_Primitive));
  28082. Primitives.Sphere = Sphere;
  28083. var Disc = (function (_super) {
  28084. __extends(Disc, _super);
  28085. // Members
  28086. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28087. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28088. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28089. _this.radius = radius;
  28090. _this.tessellation = tessellation;
  28091. _this.side = side;
  28092. return _this;
  28093. }
  28094. Disc.prototype._regenerateVertexData = function () {
  28095. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28096. };
  28097. Disc.prototype.copy = function (id) {
  28098. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28099. };
  28100. return Disc;
  28101. }(_Primitive));
  28102. Primitives.Disc = Disc;
  28103. var Cylinder = (function (_super) {
  28104. __extends(Cylinder, _super);
  28105. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28106. if (subdivisions === void 0) { subdivisions = 1; }
  28107. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28108. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28109. _this.height = height;
  28110. _this.diameterTop = diameterTop;
  28111. _this.diameterBottom = diameterBottom;
  28112. _this.tessellation = tessellation;
  28113. _this.subdivisions = subdivisions;
  28114. _this.side = side;
  28115. return _this;
  28116. }
  28117. Cylinder.prototype._regenerateVertexData = function () {
  28118. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28119. };
  28120. Cylinder.prototype.copy = function (id) {
  28121. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28122. };
  28123. Cylinder.prototype.serialize = function () {
  28124. var serializationObject = _super.prototype.serialize.call(this);
  28125. serializationObject.height = this.height;
  28126. serializationObject.diameterTop = this.diameterTop;
  28127. serializationObject.diameterBottom = this.diameterBottom;
  28128. serializationObject.tessellation = this.tessellation;
  28129. return serializationObject;
  28130. };
  28131. Cylinder.Parse = function (parsedCylinder, scene) {
  28132. if (scene.getGeometryByID(parsedCylinder.id)) {
  28133. return null; // null since geometry could be something else than a cylinder...
  28134. }
  28135. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28136. if (BABYLON.Tags) {
  28137. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28138. }
  28139. scene.pushGeometry(cylinder, true);
  28140. return cylinder;
  28141. };
  28142. return Cylinder;
  28143. }(_Primitive));
  28144. Primitives.Cylinder = Cylinder;
  28145. var Torus = (function (_super) {
  28146. __extends(Torus, _super);
  28147. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28148. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28149. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28150. _this.diameter = diameter;
  28151. _this.thickness = thickness;
  28152. _this.tessellation = tessellation;
  28153. _this.side = side;
  28154. return _this;
  28155. }
  28156. Torus.prototype._regenerateVertexData = function () {
  28157. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28158. };
  28159. Torus.prototype.copy = function (id) {
  28160. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28161. };
  28162. Torus.prototype.serialize = function () {
  28163. var serializationObject = _super.prototype.serialize.call(this);
  28164. serializationObject.diameter = this.diameter;
  28165. serializationObject.thickness = this.thickness;
  28166. serializationObject.tessellation = this.tessellation;
  28167. return serializationObject;
  28168. };
  28169. Torus.Parse = function (parsedTorus, scene) {
  28170. if (scene.getGeometryByID(parsedTorus.id)) {
  28171. return null; // null since geometry could be something else than a torus...
  28172. }
  28173. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28174. if (BABYLON.Tags) {
  28175. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28176. }
  28177. scene.pushGeometry(torus, true);
  28178. return torus;
  28179. };
  28180. return Torus;
  28181. }(_Primitive));
  28182. Primitives.Torus = Torus;
  28183. var Ground = (function (_super) {
  28184. __extends(Ground, _super);
  28185. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28186. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28187. _this.width = width;
  28188. _this.height = height;
  28189. _this.subdivisions = subdivisions;
  28190. return _this;
  28191. }
  28192. Ground.prototype._regenerateVertexData = function () {
  28193. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28194. };
  28195. Ground.prototype.copy = function (id) {
  28196. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28197. };
  28198. Ground.prototype.serialize = function () {
  28199. var serializationObject = _super.prototype.serialize.call(this);
  28200. serializationObject.width = this.width;
  28201. serializationObject.height = this.height;
  28202. serializationObject.subdivisions = this.subdivisions;
  28203. return serializationObject;
  28204. };
  28205. Ground.Parse = function (parsedGround, scene) {
  28206. if (scene.getGeometryByID(parsedGround.id)) {
  28207. return null; // null since geometry could be something else than a ground...
  28208. }
  28209. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28210. if (BABYLON.Tags) {
  28211. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28212. }
  28213. scene.pushGeometry(ground, true);
  28214. return ground;
  28215. };
  28216. return Ground;
  28217. }(_Primitive));
  28218. Primitives.Ground = Ground;
  28219. var TiledGround = (function (_super) {
  28220. __extends(TiledGround, _super);
  28221. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28222. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28223. _this.xmin = xmin;
  28224. _this.zmin = zmin;
  28225. _this.xmax = xmax;
  28226. _this.zmax = zmax;
  28227. _this.subdivisions = subdivisions;
  28228. _this.precision = precision;
  28229. return _this;
  28230. }
  28231. TiledGround.prototype._regenerateVertexData = function () {
  28232. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28233. };
  28234. TiledGround.prototype.copy = function (id) {
  28235. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28236. };
  28237. return TiledGround;
  28238. }(_Primitive));
  28239. Primitives.TiledGround = TiledGround;
  28240. var Plane = (function (_super) {
  28241. __extends(Plane, _super);
  28242. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28243. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28244. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28245. _this.size = size;
  28246. _this.side = side;
  28247. return _this;
  28248. }
  28249. Plane.prototype._regenerateVertexData = function () {
  28250. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28251. };
  28252. Plane.prototype.copy = function (id) {
  28253. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28254. };
  28255. Plane.prototype.serialize = function () {
  28256. var serializationObject = _super.prototype.serialize.call(this);
  28257. serializationObject.size = this.size;
  28258. return serializationObject;
  28259. };
  28260. Plane.Parse = function (parsedPlane, scene) {
  28261. if (scene.getGeometryByID(parsedPlane.id)) {
  28262. return null; // null since geometry could be something else than a ground...
  28263. }
  28264. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28265. if (BABYLON.Tags) {
  28266. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28267. }
  28268. scene.pushGeometry(plane, true);
  28269. return plane;
  28270. };
  28271. return Plane;
  28272. }(_Primitive));
  28273. Primitives.Plane = Plane;
  28274. var TorusKnot = (function (_super) {
  28275. __extends(TorusKnot, _super);
  28276. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28277. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28278. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28279. _this.radius = radius;
  28280. _this.tube = tube;
  28281. _this.radialSegments = radialSegments;
  28282. _this.tubularSegments = tubularSegments;
  28283. _this.p = p;
  28284. _this.q = q;
  28285. _this.side = side;
  28286. return _this;
  28287. }
  28288. TorusKnot.prototype._regenerateVertexData = function () {
  28289. 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 });
  28290. };
  28291. TorusKnot.prototype.copy = function (id) {
  28292. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28293. };
  28294. TorusKnot.prototype.serialize = function () {
  28295. var serializationObject = _super.prototype.serialize.call(this);
  28296. serializationObject.radius = this.radius;
  28297. serializationObject.tube = this.tube;
  28298. serializationObject.radialSegments = this.radialSegments;
  28299. serializationObject.tubularSegments = this.tubularSegments;
  28300. serializationObject.p = this.p;
  28301. serializationObject.q = this.q;
  28302. return serializationObject;
  28303. };
  28304. ;
  28305. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28306. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28307. return null; // null since geometry could be something else than a ground...
  28308. }
  28309. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28310. if (BABYLON.Tags) {
  28311. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28312. }
  28313. scene.pushGeometry(torusKnot, true);
  28314. return torusKnot;
  28315. };
  28316. return TorusKnot;
  28317. }(_Primitive));
  28318. Primitives.TorusKnot = TorusKnot;
  28319. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28320. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28321. })(BABYLON || (BABYLON = {}));
  28322. //# sourceMappingURL=babylon.geometry.js.map
  28323. var BABYLON;
  28324. (function (BABYLON) {
  28325. var PostProcessManager = (function () {
  28326. function PostProcessManager(scene) {
  28327. this._vertexBuffers = {};
  28328. this._scene = scene;
  28329. }
  28330. PostProcessManager.prototype._prepareBuffers = function () {
  28331. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28332. return;
  28333. }
  28334. // VBO
  28335. var vertices = [];
  28336. vertices.push(1, 1);
  28337. vertices.push(-1, 1);
  28338. vertices.push(-1, -1);
  28339. vertices.push(1, -1);
  28340. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28341. // Indices
  28342. var indices = [];
  28343. indices.push(0);
  28344. indices.push(1);
  28345. indices.push(2);
  28346. indices.push(0);
  28347. indices.push(2);
  28348. indices.push(3);
  28349. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28350. };
  28351. // Methods
  28352. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28353. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28354. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28355. return false;
  28356. }
  28357. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28358. return true;
  28359. };
  28360. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28361. var engine = this._scene.getEngine();
  28362. for (var index = 0; index < postProcesses.length; index++) {
  28363. if (index < postProcesses.length - 1) {
  28364. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28365. }
  28366. else {
  28367. if (targetTexture) {
  28368. engine.bindFramebuffer(targetTexture);
  28369. }
  28370. else {
  28371. engine.restoreDefaultFramebuffer();
  28372. }
  28373. }
  28374. var pp = postProcesses[index];
  28375. var effect = pp.apply();
  28376. if (effect) {
  28377. pp.onBeforeRenderObservable.notifyObservers(effect);
  28378. // VBOs
  28379. this._prepareBuffers();
  28380. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28381. // Draw order
  28382. engine.draw(true, 0, 6);
  28383. pp.onAfterRenderObservable.notifyObservers(effect);
  28384. }
  28385. }
  28386. // Restore depth buffer
  28387. engine.setDepthBuffer(true);
  28388. engine.setDepthWrite(true);
  28389. };
  28390. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28391. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28392. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28393. return;
  28394. }
  28395. var engine = this._scene.getEngine();
  28396. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28397. if (index < len - 1) {
  28398. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28399. }
  28400. else {
  28401. if (targetTexture) {
  28402. engine.bindFramebuffer(targetTexture, faceIndex);
  28403. }
  28404. else {
  28405. engine.restoreDefaultFramebuffer();
  28406. }
  28407. }
  28408. if (doNotPresent) {
  28409. break;
  28410. }
  28411. var pp = postProcesses[index];
  28412. var effect = pp.apply();
  28413. if (effect) {
  28414. pp.onBeforeRenderObservable.notifyObservers(effect);
  28415. // VBOs
  28416. this._prepareBuffers();
  28417. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28418. // Draw order
  28419. engine.draw(true, 0, 6);
  28420. pp.onAfterRenderObservable.notifyObservers(effect);
  28421. }
  28422. }
  28423. // Restore states
  28424. engine.setDepthBuffer(true);
  28425. engine.setDepthWrite(true);
  28426. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28427. };
  28428. PostProcessManager.prototype.dispose = function () {
  28429. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28430. if (buffer) {
  28431. buffer.dispose();
  28432. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28433. }
  28434. if (this._indexBuffer) {
  28435. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28436. this._indexBuffer = null;
  28437. }
  28438. };
  28439. return PostProcessManager;
  28440. }());
  28441. BABYLON.PostProcessManager = PostProcessManager;
  28442. })(BABYLON || (BABYLON = {}));
  28443. //# sourceMappingURL=babylon.postProcessManager.js.map
  28444. var BABYLON;
  28445. (function (BABYLON) {
  28446. var AnimationRange = (function () {
  28447. function AnimationRange(name, from, to) {
  28448. this.name = name;
  28449. this.from = from;
  28450. this.to = to;
  28451. }
  28452. AnimationRange.prototype.clone = function () {
  28453. return new AnimationRange(this.name, this.from, this.to);
  28454. };
  28455. return AnimationRange;
  28456. }());
  28457. BABYLON.AnimationRange = AnimationRange;
  28458. /**
  28459. * Composed of a frame, and an action function
  28460. */
  28461. var AnimationEvent = (function () {
  28462. function AnimationEvent(frame, action, onlyOnce) {
  28463. this.frame = frame;
  28464. this.action = action;
  28465. this.onlyOnce = onlyOnce;
  28466. this.isDone = false;
  28467. }
  28468. return AnimationEvent;
  28469. }());
  28470. BABYLON.AnimationEvent = AnimationEvent;
  28471. var PathCursor = (function () {
  28472. function PathCursor(path) {
  28473. this.path = path;
  28474. this._onchange = new Array();
  28475. this.value = 0;
  28476. this.animations = new Array();
  28477. }
  28478. PathCursor.prototype.getPoint = function () {
  28479. var point = this.path.getPointAtLengthPosition(this.value);
  28480. return new BABYLON.Vector3(point.x, 0, point.y);
  28481. };
  28482. PathCursor.prototype.moveAhead = function (step) {
  28483. if (step === void 0) { step = 0.002; }
  28484. this.move(step);
  28485. return this;
  28486. };
  28487. PathCursor.prototype.moveBack = function (step) {
  28488. if (step === void 0) { step = 0.002; }
  28489. this.move(-step);
  28490. return this;
  28491. };
  28492. PathCursor.prototype.move = function (step) {
  28493. if (Math.abs(step) > 1) {
  28494. throw "step size should be less than 1.";
  28495. }
  28496. this.value += step;
  28497. this.ensureLimits();
  28498. this.raiseOnChange();
  28499. return this;
  28500. };
  28501. PathCursor.prototype.ensureLimits = function () {
  28502. while (this.value > 1) {
  28503. this.value -= 1;
  28504. }
  28505. while (this.value < 0) {
  28506. this.value += 1;
  28507. }
  28508. return this;
  28509. };
  28510. // used by animation engine
  28511. PathCursor.prototype.markAsDirty = function (propertyName) {
  28512. this.ensureLimits();
  28513. this.raiseOnChange();
  28514. return this;
  28515. };
  28516. PathCursor.prototype.raiseOnChange = function () {
  28517. var _this = this;
  28518. this._onchange.forEach(function (f) { return f(_this); });
  28519. return this;
  28520. };
  28521. PathCursor.prototype.onchange = function (f) {
  28522. this._onchange.push(f);
  28523. return this;
  28524. };
  28525. return PathCursor;
  28526. }());
  28527. BABYLON.PathCursor = PathCursor;
  28528. var Animation = (function () {
  28529. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28530. this.name = name;
  28531. this.targetProperty = targetProperty;
  28532. this.framePerSecond = framePerSecond;
  28533. this.dataType = dataType;
  28534. this.loopMode = loopMode;
  28535. this.enableBlending = enableBlending;
  28536. this._offsetsCache = {};
  28537. this._highLimitsCache = {};
  28538. this._stopped = false;
  28539. this._blendingFactor = 0;
  28540. // The set of event that will be linked to this animation
  28541. this._events = new Array();
  28542. this.allowMatricesInterpolation = false;
  28543. this.blendingSpeed = 0.01;
  28544. this._ranges = {};
  28545. this.targetPropertyPath = targetProperty.split(".");
  28546. this.dataType = dataType;
  28547. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28548. }
  28549. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28550. var dataType = undefined;
  28551. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28552. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28553. }
  28554. else if (from instanceof BABYLON.Quaternion) {
  28555. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28556. }
  28557. else if (from instanceof BABYLON.Vector3) {
  28558. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28559. }
  28560. else if (from instanceof BABYLON.Vector2) {
  28561. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28562. }
  28563. else if (from instanceof BABYLON.Color3) {
  28564. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28565. }
  28566. else if (from instanceof BABYLON.Size) {
  28567. dataType = Animation.ANIMATIONTYPE_SIZE;
  28568. }
  28569. if (dataType == undefined) {
  28570. return null;
  28571. }
  28572. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28573. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28574. animation.setKeys(keys);
  28575. if (easingFunction !== undefined) {
  28576. animation.setEasingFunction(easingFunction);
  28577. }
  28578. return animation;
  28579. };
  28580. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28581. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28582. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28583. };
  28584. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28585. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28586. node.animations.push(animation);
  28587. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28588. };
  28589. // Methods
  28590. /**
  28591. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28592. */
  28593. Animation.prototype.toString = function (fullDetails) {
  28594. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28595. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28596. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28597. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28598. if (fullDetails) {
  28599. ret += ", Ranges: {";
  28600. var first = true;
  28601. for (var name in this._ranges) {
  28602. if (first) {
  28603. ret += ", ";
  28604. first = false;
  28605. }
  28606. ret += name;
  28607. }
  28608. ret += "}";
  28609. }
  28610. return ret;
  28611. };
  28612. /**
  28613. * Add an event to this animation.
  28614. */
  28615. Animation.prototype.addEvent = function (event) {
  28616. this._events.push(event);
  28617. };
  28618. /**
  28619. * Remove all events found at the given frame
  28620. * @param frame
  28621. */
  28622. Animation.prototype.removeEvents = function (frame) {
  28623. for (var index = 0; index < this._events.length; index++) {
  28624. if (this._events[index].frame === frame) {
  28625. this._events.splice(index, 1);
  28626. index--;
  28627. }
  28628. }
  28629. };
  28630. Animation.prototype.createRange = function (name, from, to) {
  28631. // check name not already in use; could happen for bones after serialized
  28632. if (!this._ranges[name]) {
  28633. this._ranges[name] = new AnimationRange(name, from, to);
  28634. }
  28635. };
  28636. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28637. if (deleteFrames === void 0) { deleteFrames = true; }
  28638. if (this._ranges[name]) {
  28639. if (deleteFrames) {
  28640. var from = this._ranges[name].from;
  28641. var to = this._ranges[name].to;
  28642. // this loop MUST go high to low for multiple splices to work
  28643. for (var key = this._keys.length - 1; key >= 0; key--) {
  28644. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28645. this._keys.splice(key, 1);
  28646. }
  28647. }
  28648. }
  28649. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28650. }
  28651. };
  28652. Animation.prototype.getRange = function (name) {
  28653. return this._ranges[name];
  28654. };
  28655. Animation.prototype.reset = function () {
  28656. this._offsetsCache = {};
  28657. this._highLimitsCache = {};
  28658. this.currentFrame = 0;
  28659. this._blendingFactor = 0;
  28660. this._originalBlendValue = null;
  28661. };
  28662. Animation.prototype.isStopped = function () {
  28663. return this._stopped;
  28664. };
  28665. Animation.prototype.getKeys = function () {
  28666. return this._keys;
  28667. };
  28668. Animation.prototype.getHighestFrame = function () {
  28669. var ret = 0;
  28670. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28671. if (ret < this._keys[key].frame) {
  28672. ret = this._keys[key].frame;
  28673. }
  28674. }
  28675. return ret;
  28676. };
  28677. Animation.prototype.getEasingFunction = function () {
  28678. return this._easingFunction;
  28679. };
  28680. Animation.prototype.setEasingFunction = function (easingFunction) {
  28681. this._easingFunction = easingFunction;
  28682. };
  28683. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28684. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  28685. };
  28686. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28687. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28688. };
  28689. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28690. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28691. };
  28692. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28693. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  28694. };
  28695. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28696. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28697. };
  28698. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28699. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28700. };
  28701. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28702. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28703. };
  28704. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28705. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28706. };
  28707. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28708. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28709. };
  28710. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28711. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28712. };
  28713. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28714. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28715. };
  28716. Animation.prototype.clone = function () {
  28717. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28718. clone.enableBlending = this.enableBlending;
  28719. clone.blendingSpeed = this.blendingSpeed;
  28720. if (this._keys) {
  28721. clone.setKeys(this._keys);
  28722. }
  28723. if (this._ranges) {
  28724. clone._ranges = {};
  28725. for (var name in this._ranges) {
  28726. clone._ranges[name] = this._ranges[name].clone();
  28727. }
  28728. }
  28729. return clone;
  28730. };
  28731. Animation.prototype.setKeys = function (values) {
  28732. this._keys = values.slice(0);
  28733. this._offsetsCache = {};
  28734. this._highLimitsCache = {};
  28735. };
  28736. Animation.prototype._getKeyValue = function (value) {
  28737. if (typeof value === "function") {
  28738. return value();
  28739. }
  28740. return value;
  28741. };
  28742. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28743. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28744. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28745. }
  28746. this.currentFrame = currentFrame;
  28747. // Try to get a hash to find the right key
  28748. 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));
  28749. if (this._keys[startKeyIndex].frame >= currentFrame) {
  28750. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  28751. startKeyIndex--;
  28752. }
  28753. }
  28754. for (var key = startKeyIndex; key < this._keys.length; key++) {
  28755. var endKey = this._keys[key + 1];
  28756. if (endKey.frame >= currentFrame) {
  28757. var startKey = this._keys[key];
  28758. var startValue = this._getKeyValue(startKey.value);
  28759. var endValue = this._getKeyValue(endKey.value);
  28760. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  28761. var frameDelta = endKey.frame - startKey.frame;
  28762. // gradient : percent of currentFrame between the frame inf and the frame sup
  28763. var gradient = (currentFrame - startKey.frame) / frameDelta;
  28764. // check for easingFunction and correction of gradient
  28765. if (this._easingFunction != null) {
  28766. gradient = this._easingFunction.ease(gradient);
  28767. }
  28768. switch (this.dataType) {
  28769. // Float
  28770. case Animation.ANIMATIONTYPE_FLOAT:
  28771. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  28772. switch (loopMode) {
  28773. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28774. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28775. return floatValue;
  28776. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28777. return offsetValue * repeatCount + floatValue;
  28778. }
  28779. break;
  28780. // Quaternion
  28781. case Animation.ANIMATIONTYPE_QUATERNION:
  28782. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28783. switch (loopMode) {
  28784. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28785. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28786. return quatValue;
  28787. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28788. return quatValue.add(offsetValue.scale(repeatCount));
  28789. }
  28790. return quatValue;
  28791. // Vector3
  28792. case Animation.ANIMATIONTYPE_VECTOR3:
  28793. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  28794. switch (loopMode) {
  28795. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28796. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28797. return vec3Value;
  28798. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28799. return vec3Value.add(offsetValue.scale(repeatCount));
  28800. }
  28801. // Vector2
  28802. case Animation.ANIMATIONTYPE_VECTOR2:
  28803. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  28804. switch (loopMode) {
  28805. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28806. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28807. return vec2Value;
  28808. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28809. return vec2Value.add(offsetValue.scale(repeatCount));
  28810. }
  28811. // Size
  28812. case Animation.ANIMATIONTYPE_SIZE:
  28813. switch (loopMode) {
  28814. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28815. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28816. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28817. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28818. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28819. }
  28820. // Color3
  28821. case Animation.ANIMATIONTYPE_COLOR3:
  28822. switch (loopMode) {
  28823. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28824. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28825. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28826. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28827. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28828. }
  28829. // Matrix
  28830. case Animation.ANIMATIONTYPE_MATRIX:
  28831. switch (loopMode) {
  28832. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28833. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28834. if (this.allowMatricesInterpolation) {
  28835. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28836. }
  28837. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28838. return startValue;
  28839. }
  28840. default:
  28841. break;
  28842. }
  28843. break;
  28844. }
  28845. }
  28846. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28847. };
  28848. Animation.prototype.setValue = function (currentValue, blend) {
  28849. if (blend === void 0) { blend = false; }
  28850. // Set value
  28851. var path;
  28852. var destination;
  28853. if (this.targetPropertyPath.length > 1) {
  28854. var property = this._target[this.targetPropertyPath[0]];
  28855. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28856. property = property[this.targetPropertyPath[index]];
  28857. }
  28858. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28859. destination = property;
  28860. }
  28861. else {
  28862. path = this.targetPropertyPath[0];
  28863. destination = this._target;
  28864. }
  28865. // Blending
  28866. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28867. if (!this._originalBlendValue) {
  28868. if (destination[path].clone) {
  28869. this._originalBlendValue = destination[path].clone();
  28870. }
  28871. else {
  28872. this._originalBlendValue = destination[path];
  28873. }
  28874. }
  28875. if (this._originalBlendValue.prototype) {
  28876. if (this._originalBlendValue.prototype.Lerp) {
  28877. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28878. }
  28879. else {
  28880. destination[path] = currentValue;
  28881. }
  28882. }
  28883. else if (this._originalBlendValue.m) {
  28884. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28885. }
  28886. else {
  28887. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28888. }
  28889. this._blendingFactor += this.blendingSpeed;
  28890. }
  28891. else {
  28892. destination[path] = currentValue;
  28893. }
  28894. if (this._target.markAsDirty) {
  28895. this._target.markAsDirty(this.targetProperty);
  28896. }
  28897. };
  28898. Animation.prototype.goToFrame = function (frame) {
  28899. if (frame < this._keys[0].frame) {
  28900. frame = this._keys[0].frame;
  28901. }
  28902. else if (frame > this._keys[this._keys.length - 1].frame) {
  28903. frame = this._keys[this._keys.length - 1].frame;
  28904. }
  28905. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28906. this.setValue(currentValue);
  28907. };
  28908. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28909. if (blend === void 0) { blend = false; }
  28910. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28911. this._stopped = true;
  28912. return false;
  28913. }
  28914. var returnValue = true;
  28915. // Adding a start key at frame 0 if missing
  28916. if (this._keys[0].frame !== 0) {
  28917. var newKey = { frame: 0, value: this._keys[0].value };
  28918. this._keys.splice(0, 0, newKey);
  28919. }
  28920. // Check limits
  28921. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28922. from = this._keys[0].frame;
  28923. }
  28924. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28925. to = this._keys[this._keys.length - 1].frame;
  28926. }
  28927. //to and from cannot be the same key
  28928. if (from === to) {
  28929. from++;
  28930. }
  28931. // Compute ratio
  28932. var range = to - from;
  28933. var offsetValue;
  28934. // ratio represents the frame delta between from and to
  28935. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28936. var highLimitValue = 0;
  28937. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  28938. returnValue = false;
  28939. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28940. }
  28941. else {
  28942. // Get max value if required
  28943. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28944. var keyOffset = to.toString() + from.toString();
  28945. if (!this._offsetsCache[keyOffset]) {
  28946. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28947. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28948. switch (this.dataType) {
  28949. // Float
  28950. case Animation.ANIMATIONTYPE_FLOAT:
  28951. this._offsetsCache[keyOffset] = toValue - fromValue;
  28952. break;
  28953. // Quaternion
  28954. case Animation.ANIMATIONTYPE_QUATERNION:
  28955. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28956. break;
  28957. // Vector3
  28958. case Animation.ANIMATIONTYPE_VECTOR3:
  28959. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28960. // Vector2
  28961. case Animation.ANIMATIONTYPE_VECTOR2:
  28962. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28963. // Size
  28964. case Animation.ANIMATIONTYPE_SIZE:
  28965. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28966. // Color3
  28967. case Animation.ANIMATIONTYPE_COLOR3:
  28968. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28969. default:
  28970. break;
  28971. }
  28972. this._highLimitsCache[keyOffset] = toValue;
  28973. }
  28974. highLimitValue = this._highLimitsCache[keyOffset];
  28975. offsetValue = this._offsetsCache[keyOffset];
  28976. }
  28977. }
  28978. if (offsetValue === undefined) {
  28979. switch (this.dataType) {
  28980. // Float
  28981. case Animation.ANIMATIONTYPE_FLOAT:
  28982. offsetValue = 0;
  28983. break;
  28984. // Quaternion
  28985. case Animation.ANIMATIONTYPE_QUATERNION:
  28986. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28987. break;
  28988. // Vector3
  28989. case Animation.ANIMATIONTYPE_VECTOR3:
  28990. offsetValue = BABYLON.Vector3.Zero();
  28991. break;
  28992. // Vector2
  28993. case Animation.ANIMATIONTYPE_VECTOR2:
  28994. offsetValue = BABYLON.Vector2.Zero();
  28995. break;
  28996. // Size
  28997. case Animation.ANIMATIONTYPE_SIZE:
  28998. offsetValue = BABYLON.Size.Zero();
  28999. break;
  29000. // Color3
  29001. case Animation.ANIMATIONTYPE_COLOR3:
  29002. offsetValue = BABYLON.Color3.Black();
  29003. }
  29004. }
  29005. // Compute value
  29006. var repeatCount = (ratio / range) >> 0;
  29007. var currentFrame = returnValue ? from + ratio % range : to;
  29008. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29009. // Set value
  29010. this.setValue(currentValue);
  29011. // Check events
  29012. for (var index = 0; index < this._events.length; index++) {
  29013. if (currentFrame >= this._events[index].frame) {
  29014. var event = this._events[index];
  29015. if (!event.isDone) {
  29016. // If event should be done only once, remove it.
  29017. if (event.onlyOnce) {
  29018. this._events.splice(index, 1);
  29019. index--;
  29020. }
  29021. event.isDone = true;
  29022. event.action();
  29023. } // Don't do anything if the event has already be done.
  29024. }
  29025. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29026. // reset event, the animation is looping
  29027. this._events[index].isDone = false;
  29028. }
  29029. }
  29030. if (!returnValue) {
  29031. this._stopped = true;
  29032. }
  29033. return returnValue;
  29034. };
  29035. Animation.prototype.serialize = function () {
  29036. var serializationObject = {};
  29037. serializationObject.name = this.name;
  29038. serializationObject.property = this.targetProperty;
  29039. serializationObject.framePerSecond = this.framePerSecond;
  29040. serializationObject.dataType = this.dataType;
  29041. serializationObject.loopBehavior = this.loopMode;
  29042. serializationObject.enableBlending = this.enableBlending;
  29043. serializationObject.blendingSpeed = this.blendingSpeed;
  29044. var dataType = this.dataType;
  29045. serializationObject.keys = [];
  29046. var keys = this.getKeys();
  29047. for (var index = 0; index < keys.length; index++) {
  29048. var animationKey = keys[index];
  29049. var key = {};
  29050. key.frame = animationKey.frame;
  29051. switch (dataType) {
  29052. case Animation.ANIMATIONTYPE_FLOAT:
  29053. key.values = [animationKey.value];
  29054. break;
  29055. case Animation.ANIMATIONTYPE_QUATERNION:
  29056. case Animation.ANIMATIONTYPE_MATRIX:
  29057. case Animation.ANIMATIONTYPE_VECTOR3:
  29058. case Animation.ANIMATIONTYPE_COLOR3:
  29059. key.values = animationKey.value.asArray();
  29060. break;
  29061. }
  29062. serializationObject.keys.push(key);
  29063. }
  29064. serializationObject.ranges = [];
  29065. for (var name in this._ranges) {
  29066. var range = {};
  29067. range.name = name;
  29068. range.from = this._ranges[name].from;
  29069. range.to = this._ranges[name].to;
  29070. serializationObject.ranges.push(range);
  29071. }
  29072. return serializationObject;
  29073. };
  29074. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29075. get: function () {
  29076. return Animation._ANIMATIONTYPE_FLOAT;
  29077. },
  29078. enumerable: true,
  29079. configurable: true
  29080. });
  29081. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29082. get: function () {
  29083. return Animation._ANIMATIONTYPE_VECTOR3;
  29084. },
  29085. enumerable: true,
  29086. configurable: true
  29087. });
  29088. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29089. get: function () {
  29090. return Animation._ANIMATIONTYPE_VECTOR2;
  29091. },
  29092. enumerable: true,
  29093. configurable: true
  29094. });
  29095. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29096. get: function () {
  29097. return Animation._ANIMATIONTYPE_SIZE;
  29098. },
  29099. enumerable: true,
  29100. configurable: true
  29101. });
  29102. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29103. get: function () {
  29104. return Animation._ANIMATIONTYPE_QUATERNION;
  29105. },
  29106. enumerable: true,
  29107. configurable: true
  29108. });
  29109. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29110. get: function () {
  29111. return Animation._ANIMATIONTYPE_MATRIX;
  29112. },
  29113. enumerable: true,
  29114. configurable: true
  29115. });
  29116. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29117. get: function () {
  29118. return Animation._ANIMATIONTYPE_COLOR3;
  29119. },
  29120. enumerable: true,
  29121. configurable: true
  29122. });
  29123. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29124. get: function () {
  29125. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29126. },
  29127. enumerable: true,
  29128. configurable: true
  29129. });
  29130. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29131. get: function () {
  29132. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29133. },
  29134. enumerable: true,
  29135. configurable: true
  29136. });
  29137. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29138. get: function () {
  29139. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29140. },
  29141. enumerable: true,
  29142. configurable: true
  29143. });
  29144. Animation.Parse = function (parsedAnimation) {
  29145. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29146. var dataType = parsedAnimation.dataType;
  29147. var keys = [];
  29148. var data;
  29149. var index;
  29150. if (parsedAnimation.enableBlending) {
  29151. animation.enableBlending = parsedAnimation.enableBlending;
  29152. }
  29153. if (parsedAnimation.blendingSpeed) {
  29154. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  29155. }
  29156. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29157. var key = parsedAnimation.keys[index];
  29158. switch (dataType) {
  29159. case Animation.ANIMATIONTYPE_FLOAT:
  29160. data = key.values[0];
  29161. break;
  29162. case Animation.ANIMATIONTYPE_QUATERNION:
  29163. data = BABYLON.Quaternion.FromArray(key.values);
  29164. break;
  29165. case Animation.ANIMATIONTYPE_MATRIX:
  29166. data = BABYLON.Matrix.FromArray(key.values);
  29167. break;
  29168. case Animation.ANIMATIONTYPE_COLOR3:
  29169. data = BABYLON.Color3.FromArray(key.values);
  29170. break;
  29171. case Animation.ANIMATIONTYPE_VECTOR3:
  29172. default:
  29173. data = BABYLON.Vector3.FromArray(key.values);
  29174. break;
  29175. }
  29176. keys.push({
  29177. frame: key.frame,
  29178. value: data
  29179. });
  29180. }
  29181. animation.setKeys(keys);
  29182. if (parsedAnimation.ranges) {
  29183. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29184. data = parsedAnimation.ranges[index];
  29185. animation.createRange(data.name, data.from, data.to);
  29186. }
  29187. }
  29188. return animation;
  29189. };
  29190. Animation.AppendSerializedAnimations = function (source, destination) {
  29191. if (source.animations) {
  29192. destination.animations = [];
  29193. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29194. var animation = source.animations[animationIndex];
  29195. destination.animations.push(animation.serialize());
  29196. }
  29197. }
  29198. };
  29199. return Animation;
  29200. }());
  29201. // Statics
  29202. Animation._ANIMATIONTYPE_FLOAT = 0;
  29203. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29204. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29205. Animation._ANIMATIONTYPE_MATRIX = 3;
  29206. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29207. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29208. Animation._ANIMATIONTYPE_SIZE = 6;
  29209. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29210. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29211. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29212. BABYLON.Animation = Animation;
  29213. })(BABYLON || (BABYLON = {}));
  29214. //# sourceMappingURL=babylon.animation.js.map
  29215. var BABYLON;
  29216. (function (BABYLON) {
  29217. var Animatable = (function () {
  29218. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29219. if (fromFrame === void 0) { fromFrame = 0; }
  29220. if (toFrame === void 0) { toFrame = 100; }
  29221. if (loopAnimation === void 0) { loopAnimation = false; }
  29222. if (speedRatio === void 0) { speedRatio = 1.0; }
  29223. this.target = target;
  29224. this.fromFrame = fromFrame;
  29225. this.toFrame = toFrame;
  29226. this.loopAnimation = loopAnimation;
  29227. this.speedRatio = speedRatio;
  29228. this.onAnimationEnd = onAnimationEnd;
  29229. this._localDelayOffset = null;
  29230. this._pausedDelay = null;
  29231. this._animations = new Array();
  29232. this._paused = false;
  29233. this.animationStarted = false;
  29234. if (animations) {
  29235. this.appendAnimations(target, animations);
  29236. }
  29237. this._scene = scene;
  29238. scene._activeAnimatables.push(this);
  29239. }
  29240. // Methods
  29241. Animatable.prototype.getAnimations = function () {
  29242. return this._animations;
  29243. };
  29244. Animatable.prototype.appendAnimations = function (target, animations) {
  29245. for (var index = 0; index < animations.length; index++) {
  29246. var animation = animations[index];
  29247. animation._target = target;
  29248. this._animations.push(animation);
  29249. }
  29250. };
  29251. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29252. var animations = this._animations;
  29253. for (var index = 0; index < animations.length; index++) {
  29254. if (animations[index].targetProperty === property) {
  29255. return animations[index];
  29256. }
  29257. }
  29258. return null;
  29259. };
  29260. Animatable.prototype.reset = function () {
  29261. var animations = this._animations;
  29262. for (var index = 0; index < animations.length; index++) {
  29263. animations[index].reset();
  29264. }
  29265. this._localDelayOffset = null;
  29266. this._pausedDelay = null;
  29267. };
  29268. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29269. var animations = this._animations;
  29270. for (var index = 0; index < animations.length; index++) {
  29271. animations[index].enableBlending = true;
  29272. animations[index].blendingSpeed = blendingSpeed;
  29273. }
  29274. };
  29275. Animatable.prototype.disableBlending = function () {
  29276. var animations = this._animations;
  29277. for (var index = 0; index < animations.length; index++) {
  29278. animations[index].enableBlending = false;
  29279. }
  29280. };
  29281. Animatable.prototype.goToFrame = function (frame) {
  29282. var animations = this._animations;
  29283. if (animations[0]) {
  29284. var fps = animations[0].framePerSecond;
  29285. var currentFrame = animations[0].currentFrame;
  29286. var adjustTime = frame - currentFrame;
  29287. var delay = adjustTime * 1000 / fps;
  29288. this._localDelayOffset -= delay;
  29289. }
  29290. for (var index = 0; index < animations.length; index++) {
  29291. animations[index].goToFrame(frame);
  29292. }
  29293. };
  29294. Animatable.prototype.pause = function () {
  29295. if (this._paused) {
  29296. return;
  29297. }
  29298. this._paused = true;
  29299. };
  29300. Animatable.prototype.restart = function () {
  29301. this._paused = false;
  29302. };
  29303. Animatable.prototype.stop = function (animationName) {
  29304. if (animationName) {
  29305. var idx = this._scene._activeAnimatables.indexOf(this);
  29306. if (idx > -1) {
  29307. var animations = this._animations;
  29308. for (var index = animations.length - 1; index >= 0; index--) {
  29309. if (typeof animationName === "string" && animations[index].name != animationName) {
  29310. continue;
  29311. }
  29312. animations[index].reset();
  29313. animations.splice(index, 1);
  29314. }
  29315. if (animations.length == 0) {
  29316. this._scene._activeAnimatables.splice(idx, 1);
  29317. if (this.onAnimationEnd) {
  29318. this.onAnimationEnd();
  29319. }
  29320. }
  29321. }
  29322. }
  29323. else {
  29324. var index = this._scene._activeAnimatables.indexOf(this);
  29325. if (index > -1) {
  29326. this._scene._activeAnimatables.splice(index, 1);
  29327. var animations = this._animations;
  29328. for (var index = 0; index < animations.length; index++) {
  29329. animations[index].reset();
  29330. }
  29331. if (this.onAnimationEnd) {
  29332. this.onAnimationEnd();
  29333. }
  29334. }
  29335. }
  29336. };
  29337. Animatable.prototype._animate = function (delay) {
  29338. if (this._paused) {
  29339. this.animationStarted = false;
  29340. if (this._pausedDelay === null) {
  29341. this._pausedDelay = delay;
  29342. }
  29343. return true;
  29344. }
  29345. if (this._localDelayOffset === null) {
  29346. this._localDelayOffset = delay;
  29347. }
  29348. else if (this._pausedDelay !== null) {
  29349. this._localDelayOffset += delay - this._pausedDelay;
  29350. this._pausedDelay = null;
  29351. }
  29352. // Animating
  29353. var running = false;
  29354. var animations = this._animations;
  29355. var index;
  29356. for (index = 0; index < animations.length; index++) {
  29357. var animation = animations[index];
  29358. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29359. running = running || isRunning;
  29360. }
  29361. this.animationStarted = running;
  29362. if (!running) {
  29363. // Remove from active animatables
  29364. index = this._scene._activeAnimatables.indexOf(this);
  29365. this._scene._activeAnimatables.splice(index, 1);
  29366. }
  29367. if (!running && this.onAnimationEnd) {
  29368. this.onAnimationEnd();
  29369. this.onAnimationEnd = null;
  29370. }
  29371. return running;
  29372. };
  29373. return Animatable;
  29374. }());
  29375. BABYLON.Animatable = Animatable;
  29376. })(BABYLON || (BABYLON = {}));
  29377. //# sourceMappingURL=babylon.animatable.js.map
  29378. var BABYLON;
  29379. (function (BABYLON) {
  29380. var EasingFunction = (function () {
  29381. function EasingFunction() {
  29382. // Properties
  29383. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29384. }
  29385. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29386. get: function () {
  29387. return EasingFunction._EASINGMODE_EASEIN;
  29388. },
  29389. enumerable: true,
  29390. configurable: true
  29391. });
  29392. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29393. get: function () {
  29394. return EasingFunction._EASINGMODE_EASEOUT;
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29400. get: function () {
  29401. return EasingFunction._EASINGMODE_EASEINOUT;
  29402. },
  29403. enumerable: true,
  29404. configurable: true
  29405. });
  29406. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29407. var n = Math.min(Math.max(easingMode, 0), 2);
  29408. this._easingMode = n;
  29409. };
  29410. EasingFunction.prototype.getEasingMode = function () {
  29411. return this._easingMode;
  29412. };
  29413. EasingFunction.prototype.easeInCore = function (gradient) {
  29414. throw new Error('You must implement this method');
  29415. };
  29416. EasingFunction.prototype.ease = function (gradient) {
  29417. switch (this._easingMode) {
  29418. case EasingFunction.EASINGMODE_EASEIN:
  29419. return this.easeInCore(gradient);
  29420. case EasingFunction.EASINGMODE_EASEOUT:
  29421. return (1 - this.easeInCore(1 - gradient));
  29422. }
  29423. if (gradient >= 0.5) {
  29424. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29425. }
  29426. return (this.easeInCore(gradient * 2) * 0.5);
  29427. };
  29428. return EasingFunction;
  29429. }());
  29430. //Statics
  29431. EasingFunction._EASINGMODE_EASEIN = 0;
  29432. EasingFunction._EASINGMODE_EASEOUT = 1;
  29433. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29434. BABYLON.EasingFunction = EasingFunction;
  29435. var CircleEase = (function (_super) {
  29436. __extends(CircleEase, _super);
  29437. function CircleEase() {
  29438. return _super !== null && _super.apply(this, arguments) || this;
  29439. }
  29440. CircleEase.prototype.easeInCore = function (gradient) {
  29441. gradient = Math.max(0, Math.min(1, gradient));
  29442. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29443. };
  29444. return CircleEase;
  29445. }(EasingFunction));
  29446. BABYLON.CircleEase = CircleEase;
  29447. var BackEase = (function (_super) {
  29448. __extends(BackEase, _super);
  29449. function BackEase(amplitude) {
  29450. if (amplitude === void 0) { amplitude = 1; }
  29451. var _this = _super.call(this) || this;
  29452. _this.amplitude = amplitude;
  29453. return _this;
  29454. }
  29455. BackEase.prototype.easeInCore = function (gradient) {
  29456. var num = Math.max(0, this.amplitude);
  29457. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29458. };
  29459. return BackEase;
  29460. }(EasingFunction));
  29461. BABYLON.BackEase = BackEase;
  29462. var BounceEase = (function (_super) {
  29463. __extends(BounceEase, _super);
  29464. function BounceEase(bounces, bounciness) {
  29465. if (bounces === void 0) { bounces = 3; }
  29466. if (bounciness === void 0) { bounciness = 2; }
  29467. var _this = _super.call(this) || this;
  29468. _this.bounces = bounces;
  29469. _this.bounciness = bounciness;
  29470. return _this;
  29471. }
  29472. BounceEase.prototype.easeInCore = function (gradient) {
  29473. var y = Math.max(0.0, this.bounces);
  29474. var bounciness = this.bounciness;
  29475. if (bounciness <= 1.0) {
  29476. bounciness = 1.001;
  29477. }
  29478. var num9 = Math.pow(bounciness, y);
  29479. var num5 = 1.0 - bounciness;
  29480. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29481. var num15 = gradient * num4;
  29482. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29483. var num3 = Math.floor(num65);
  29484. var num13 = num3 + 1.0;
  29485. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29486. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29487. var num7 = (num8 + num12) * 0.5;
  29488. var num6 = gradient - num7;
  29489. var num2 = num7 - num8;
  29490. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29491. };
  29492. return BounceEase;
  29493. }(EasingFunction));
  29494. BABYLON.BounceEase = BounceEase;
  29495. var CubicEase = (function (_super) {
  29496. __extends(CubicEase, _super);
  29497. function CubicEase() {
  29498. return _super !== null && _super.apply(this, arguments) || this;
  29499. }
  29500. CubicEase.prototype.easeInCore = function (gradient) {
  29501. return (gradient * gradient * gradient);
  29502. };
  29503. return CubicEase;
  29504. }(EasingFunction));
  29505. BABYLON.CubicEase = CubicEase;
  29506. var ElasticEase = (function (_super) {
  29507. __extends(ElasticEase, _super);
  29508. function ElasticEase(oscillations, springiness) {
  29509. if (oscillations === void 0) { oscillations = 3; }
  29510. if (springiness === void 0) { springiness = 3; }
  29511. var _this = _super.call(this) || this;
  29512. _this.oscillations = oscillations;
  29513. _this.springiness = springiness;
  29514. return _this;
  29515. }
  29516. ElasticEase.prototype.easeInCore = function (gradient) {
  29517. var num2;
  29518. var num3 = Math.max(0.0, this.oscillations);
  29519. var num = Math.max(0.0, this.springiness);
  29520. if (num == 0) {
  29521. num2 = gradient;
  29522. }
  29523. else {
  29524. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29525. }
  29526. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29527. };
  29528. return ElasticEase;
  29529. }(EasingFunction));
  29530. BABYLON.ElasticEase = ElasticEase;
  29531. var ExponentialEase = (function (_super) {
  29532. __extends(ExponentialEase, _super);
  29533. function ExponentialEase(exponent) {
  29534. if (exponent === void 0) { exponent = 2; }
  29535. var _this = _super.call(this) || this;
  29536. _this.exponent = exponent;
  29537. return _this;
  29538. }
  29539. ExponentialEase.prototype.easeInCore = function (gradient) {
  29540. if (this.exponent <= 0) {
  29541. return gradient;
  29542. }
  29543. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29544. };
  29545. return ExponentialEase;
  29546. }(EasingFunction));
  29547. BABYLON.ExponentialEase = ExponentialEase;
  29548. var PowerEase = (function (_super) {
  29549. __extends(PowerEase, _super);
  29550. function PowerEase(power) {
  29551. if (power === void 0) { power = 2; }
  29552. var _this = _super.call(this) || this;
  29553. _this.power = power;
  29554. return _this;
  29555. }
  29556. PowerEase.prototype.easeInCore = function (gradient) {
  29557. var y = Math.max(0.0, this.power);
  29558. return Math.pow(gradient, y);
  29559. };
  29560. return PowerEase;
  29561. }(EasingFunction));
  29562. BABYLON.PowerEase = PowerEase;
  29563. var QuadraticEase = (function (_super) {
  29564. __extends(QuadraticEase, _super);
  29565. function QuadraticEase() {
  29566. return _super !== null && _super.apply(this, arguments) || this;
  29567. }
  29568. QuadraticEase.prototype.easeInCore = function (gradient) {
  29569. return (gradient * gradient);
  29570. };
  29571. return QuadraticEase;
  29572. }(EasingFunction));
  29573. BABYLON.QuadraticEase = QuadraticEase;
  29574. var QuarticEase = (function (_super) {
  29575. __extends(QuarticEase, _super);
  29576. function QuarticEase() {
  29577. return _super !== null && _super.apply(this, arguments) || this;
  29578. }
  29579. QuarticEase.prototype.easeInCore = function (gradient) {
  29580. return (gradient * gradient * gradient * gradient);
  29581. };
  29582. return QuarticEase;
  29583. }(EasingFunction));
  29584. BABYLON.QuarticEase = QuarticEase;
  29585. var QuinticEase = (function (_super) {
  29586. __extends(QuinticEase, _super);
  29587. function QuinticEase() {
  29588. return _super !== null && _super.apply(this, arguments) || this;
  29589. }
  29590. QuinticEase.prototype.easeInCore = function (gradient) {
  29591. return (gradient * gradient * gradient * gradient * gradient);
  29592. };
  29593. return QuinticEase;
  29594. }(EasingFunction));
  29595. BABYLON.QuinticEase = QuinticEase;
  29596. var SineEase = (function (_super) {
  29597. __extends(SineEase, _super);
  29598. function SineEase() {
  29599. return _super !== null && _super.apply(this, arguments) || this;
  29600. }
  29601. SineEase.prototype.easeInCore = function (gradient) {
  29602. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29603. };
  29604. return SineEase;
  29605. }(EasingFunction));
  29606. BABYLON.SineEase = SineEase;
  29607. var BezierCurveEase = (function (_super) {
  29608. __extends(BezierCurveEase, _super);
  29609. function BezierCurveEase(x1, y1, x2, y2) {
  29610. if (x1 === void 0) { x1 = 0; }
  29611. if (y1 === void 0) { y1 = 0; }
  29612. if (x2 === void 0) { x2 = 1; }
  29613. if (y2 === void 0) { y2 = 1; }
  29614. var _this = _super.call(this) || this;
  29615. _this.x1 = x1;
  29616. _this.y1 = y1;
  29617. _this.x2 = x2;
  29618. _this.y2 = y2;
  29619. return _this;
  29620. }
  29621. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29622. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29623. };
  29624. return BezierCurveEase;
  29625. }(EasingFunction));
  29626. BABYLON.BezierCurveEase = BezierCurveEase;
  29627. })(BABYLON || (BABYLON = {}));
  29628. //# sourceMappingURL=babylon.easing.js.map
  29629. var BABYLON;
  29630. (function (BABYLON) {
  29631. BABYLON.CameraInputTypes = {};
  29632. var CameraInputsManager = (function () {
  29633. function CameraInputsManager(camera) {
  29634. this.attached = {};
  29635. this.camera = camera;
  29636. this.checkInputs = function () { };
  29637. }
  29638. CameraInputsManager.prototype.add = function (input) {
  29639. var type = input.getSimpleName();
  29640. if (this.attached[type]) {
  29641. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29642. return;
  29643. }
  29644. this.attached[type] = input;
  29645. input.camera = this.camera;
  29646. //for checkInputs, we are dynamically creating a function
  29647. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29648. if (input.checkInputs) {
  29649. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29650. }
  29651. if (this.attachedElement) {
  29652. input.attachControl(this.attachedElement);
  29653. }
  29654. };
  29655. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29656. for (var cam in this.attached) {
  29657. var input = this.attached[cam];
  29658. if (input === inputToRemove) {
  29659. input.detachControl(this.attachedElement);
  29660. delete this.attached[cam];
  29661. this.rebuildInputCheck();
  29662. }
  29663. }
  29664. };
  29665. CameraInputsManager.prototype.removeByType = function (inputType) {
  29666. for (var cam in this.attached) {
  29667. var input = this.attached[cam];
  29668. if (input.getTypeName() === inputType) {
  29669. input.detachControl(this.attachedElement);
  29670. delete this.attached[cam];
  29671. this.rebuildInputCheck();
  29672. }
  29673. }
  29674. };
  29675. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29676. var current = this.checkInputs;
  29677. return function () {
  29678. current();
  29679. fn();
  29680. };
  29681. };
  29682. CameraInputsManager.prototype.attachInput = function (input) {
  29683. input.attachControl(this.attachedElement, this.noPreventDefault);
  29684. };
  29685. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29686. if (this.attachedElement) {
  29687. return;
  29688. }
  29689. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29690. this.attachedElement = element;
  29691. this.noPreventDefault = noPreventDefault;
  29692. for (var cam in this.attached) {
  29693. var input = this.attached[cam];
  29694. this.attached[cam].attachControl(element, noPreventDefault);
  29695. }
  29696. };
  29697. CameraInputsManager.prototype.detachElement = function (element) {
  29698. if (this.attachedElement !== element) {
  29699. return;
  29700. }
  29701. for (var cam in this.attached) {
  29702. var input = this.attached[cam];
  29703. this.attached[cam].detachControl(element);
  29704. }
  29705. this.attachedElement = null;
  29706. };
  29707. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29708. this.checkInputs = function () { };
  29709. for (var cam in this.attached) {
  29710. var input = this.attached[cam];
  29711. if (input.checkInputs) {
  29712. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29713. }
  29714. }
  29715. };
  29716. CameraInputsManager.prototype.clear = function () {
  29717. if (this.attachedElement) {
  29718. this.detachElement(this.attachedElement);
  29719. }
  29720. this.attached = {};
  29721. this.attachedElement = null;
  29722. this.checkInputs = function () { };
  29723. };
  29724. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29725. var inputs = {};
  29726. for (var cam in this.attached) {
  29727. var input = this.attached[cam];
  29728. var res = BABYLON.SerializationHelper.Serialize(input);
  29729. inputs[input.getTypeName()] = res;
  29730. }
  29731. serializedCamera.inputsmgr = inputs;
  29732. };
  29733. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29734. var parsedInputs = parsedCamera.inputsmgr;
  29735. if (parsedInputs) {
  29736. this.clear();
  29737. for (var n in parsedInputs) {
  29738. var construct = BABYLON.CameraInputTypes[n];
  29739. if (construct) {
  29740. var parsedinput = parsedInputs[n];
  29741. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29742. this.add(input);
  29743. }
  29744. }
  29745. }
  29746. else {
  29747. //2016-03-08 this part is for managing backward compatibility
  29748. for (var n in this.attached) {
  29749. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29750. if (construct) {
  29751. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29752. this.remove(this.attached[n]);
  29753. this.add(input);
  29754. }
  29755. }
  29756. }
  29757. };
  29758. return CameraInputsManager;
  29759. }());
  29760. BABYLON.CameraInputsManager = CameraInputsManager;
  29761. })(BABYLON || (BABYLON = {}));
  29762. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29763. /// <reference path="babylon.camera.ts" />
  29764. var BABYLON;
  29765. (function (BABYLON) {
  29766. var TargetCamera = (function (_super) {
  29767. __extends(TargetCamera, _super);
  29768. function TargetCamera(name, position, scene) {
  29769. var _this = _super.call(this, name, position, scene) || this;
  29770. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29771. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29772. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29773. _this.speed = 2.0;
  29774. _this.noRotationConstraint = false;
  29775. _this.lockedTarget = null;
  29776. _this._currentTarget = BABYLON.Vector3.Zero();
  29777. _this._viewMatrix = BABYLON.Matrix.Zero();
  29778. _this._camMatrix = BABYLON.Matrix.Zero();
  29779. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29780. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29781. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29782. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29783. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29784. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29785. _this._tempMatrix = BABYLON.Matrix.Zero();
  29786. return _this;
  29787. }
  29788. TargetCamera.prototype.getFrontPosition = function (distance) {
  29789. var direction = this.getTarget().subtract(this.position);
  29790. direction.normalize();
  29791. direction.scaleInPlace(distance);
  29792. return this.globalPosition.add(direction);
  29793. };
  29794. TargetCamera.prototype._getLockedTargetPosition = function () {
  29795. if (!this.lockedTarget) {
  29796. return null;
  29797. }
  29798. if (this.lockedTarget.absolutePosition) {
  29799. this.lockedTarget.computeWorldMatrix();
  29800. }
  29801. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29802. };
  29803. // Cache
  29804. TargetCamera.prototype._initCache = function () {
  29805. _super.prototype._initCache.call(this);
  29806. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29807. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29808. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29809. };
  29810. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29811. if (!ignoreParentClass) {
  29812. _super.prototype._updateCache.call(this);
  29813. }
  29814. var lockedTargetPosition = this._getLockedTargetPosition();
  29815. if (!lockedTargetPosition) {
  29816. this._cache.lockedTarget = null;
  29817. }
  29818. else {
  29819. if (!this._cache.lockedTarget) {
  29820. this._cache.lockedTarget = lockedTargetPosition.clone();
  29821. }
  29822. else {
  29823. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  29824. }
  29825. }
  29826. this._cache.rotation.copyFrom(this.rotation);
  29827. if (this.rotationQuaternion)
  29828. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29829. };
  29830. // Synchronized
  29831. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  29832. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  29833. return false;
  29834. }
  29835. var lockedTargetPosition = this._getLockedTargetPosition();
  29836. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  29837. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  29838. };
  29839. // Methods
  29840. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  29841. var engine = this.getEngine();
  29842. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  29843. };
  29844. // Target
  29845. TargetCamera.prototype.setTarget = function (target) {
  29846. this.upVector.normalize();
  29847. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  29848. this._camMatrix.invert();
  29849. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  29850. var vDir = target.subtract(this.position);
  29851. if (vDir.x >= 0.0) {
  29852. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  29853. }
  29854. else {
  29855. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  29856. }
  29857. this.rotation.z = 0;
  29858. if (isNaN(this.rotation.x)) {
  29859. this.rotation.x = 0;
  29860. }
  29861. if (isNaN(this.rotation.y)) {
  29862. this.rotation.y = 0;
  29863. }
  29864. if (isNaN(this.rotation.z)) {
  29865. this.rotation.z = 0;
  29866. }
  29867. if (this.rotationQuaternion) {
  29868. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29869. }
  29870. };
  29871. /**
  29872. * Return the current target position of the camera. This value is expressed in local space.
  29873. */
  29874. TargetCamera.prototype.getTarget = function () {
  29875. return this._currentTarget;
  29876. };
  29877. TargetCamera.prototype._decideIfNeedsToMove = function () {
  29878. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29879. };
  29880. TargetCamera.prototype._updatePosition = function () {
  29881. if (this.parent) {
  29882. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  29883. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  29884. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  29885. return;
  29886. }
  29887. this.position.addInPlace(this.cameraDirection);
  29888. };
  29889. TargetCamera.prototype._checkInputs = function () {
  29890. var needToMove = this._decideIfNeedsToMove();
  29891. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  29892. // Move
  29893. if (needToMove) {
  29894. this._updatePosition();
  29895. }
  29896. // Rotate
  29897. if (needToRotate) {
  29898. this.rotation.x += this.cameraRotation.x;
  29899. this.rotation.y += this.cameraRotation.y;
  29900. //rotate, if quaternion is set and rotation was used
  29901. if (this.rotationQuaternion) {
  29902. var len = this.rotation.lengthSquared();
  29903. if (len) {
  29904. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29905. }
  29906. }
  29907. if (!this.noRotationConstraint) {
  29908. var limit = (Math.PI / 2) * 0.95;
  29909. if (this.rotation.x > limit)
  29910. this.rotation.x = limit;
  29911. if (this.rotation.x < -limit)
  29912. this.rotation.x = -limit;
  29913. }
  29914. }
  29915. // Inertia
  29916. if (needToMove) {
  29917. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  29918. this.cameraDirection.x = 0;
  29919. }
  29920. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  29921. this.cameraDirection.y = 0;
  29922. }
  29923. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  29924. this.cameraDirection.z = 0;
  29925. }
  29926. this.cameraDirection.scaleInPlace(this.inertia);
  29927. }
  29928. if (needToRotate) {
  29929. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  29930. this.cameraRotation.x = 0;
  29931. }
  29932. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  29933. this.cameraRotation.y = 0;
  29934. }
  29935. this.cameraRotation.scaleInPlace(this.inertia);
  29936. }
  29937. _super.prototype._checkInputs.call(this);
  29938. };
  29939. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  29940. if (this.rotationQuaternion) {
  29941. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  29942. //update the up vector!
  29943. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  29944. }
  29945. else {
  29946. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  29947. }
  29948. };
  29949. TargetCamera.prototype._getViewMatrix = function () {
  29950. if (!this.lockedTarget) {
  29951. // Compute
  29952. this._updateCameraRotationMatrix();
  29953. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  29954. // Computing target and final matrix
  29955. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  29956. }
  29957. else {
  29958. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  29959. }
  29960. if (this.getScene().useRightHandedSystem) {
  29961. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29962. }
  29963. else {
  29964. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29965. }
  29966. return this._viewMatrix;
  29967. };
  29968. /**
  29969. * @override
  29970. * Override Camera.createRigCamera
  29971. */
  29972. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  29973. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29974. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  29975. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  29976. if (!this.rotationQuaternion) {
  29977. this.rotationQuaternion = new BABYLON.Quaternion();
  29978. }
  29979. rigCamera._cameraRigParams = {};
  29980. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  29981. }
  29982. return rigCamera;
  29983. }
  29984. return null;
  29985. };
  29986. /**
  29987. * @override
  29988. * Override Camera._updateRigCameras
  29989. */
  29990. TargetCamera.prototype._updateRigCameras = function () {
  29991. var camLeft = this._rigCameras[0];
  29992. var camRight = this._rigCameras[1];
  29993. switch (this.cameraRigMode) {
  29994. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  29995. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  29996. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  29997. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  29998. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  29999. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  30000. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  30001. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  30002. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  30003. camLeft.setTarget(this.getTarget());
  30004. camRight.setTarget(this.getTarget());
  30005. break;
  30006. case BABYLON.Camera.RIG_MODE_VR:
  30007. if (camLeft.rotationQuaternion) {
  30008. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30009. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30010. }
  30011. else {
  30012. camLeft.rotation.copyFrom(this.rotation);
  30013. camRight.rotation.copyFrom(this.rotation);
  30014. }
  30015. camLeft.position.copyFrom(this.position);
  30016. camRight.position.copyFrom(this.position);
  30017. break;
  30018. }
  30019. _super.prototype._updateRigCameras.call(this);
  30020. };
  30021. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30022. if (!this._rigCamTransformMatrix) {
  30023. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30024. }
  30025. var target = this.getTarget();
  30026. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30027. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30028. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30029. };
  30030. TargetCamera.prototype.getClassName = function () {
  30031. return "TargetCamera";
  30032. };
  30033. return TargetCamera;
  30034. }(BABYLON.Camera));
  30035. __decorate([
  30036. BABYLON.serializeAsVector3()
  30037. ], TargetCamera.prototype, "rotation", void 0);
  30038. __decorate([
  30039. BABYLON.serialize()
  30040. ], TargetCamera.prototype, "speed", void 0);
  30041. __decorate([
  30042. BABYLON.serializeAsMeshReference("lockedTargetId")
  30043. ], TargetCamera.prototype, "lockedTarget", void 0);
  30044. BABYLON.TargetCamera = TargetCamera;
  30045. })(BABYLON || (BABYLON = {}));
  30046. //# sourceMappingURL=babylon.targetCamera.js.map
  30047. var BABYLON;
  30048. (function (BABYLON) {
  30049. var ArcRotateCameraKeyboardMoveInput = (function () {
  30050. function ArcRotateCameraKeyboardMoveInput() {
  30051. this._keys = [];
  30052. this.keysUp = [38];
  30053. this.keysDown = [40];
  30054. this.keysLeft = [37];
  30055. this.keysRight = [39];
  30056. }
  30057. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30058. var _this = this;
  30059. element.tabIndex = 1;
  30060. this._onKeyDown = function (evt) {
  30061. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30062. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30063. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30064. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30065. var index = _this._keys.indexOf(evt.keyCode);
  30066. if (index === -1) {
  30067. _this._keys.push(evt.keyCode);
  30068. }
  30069. if (evt.preventDefault) {
  30070. if (!noPreventDefault) {
  30071. evt.preventDefault();
  30072. }
  30073. }
  30074. }
  30075. };
  30076. this._onKeyUp = function (evt) {
  30077. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30078. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30079. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30080. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30081. var index = _this._keys.indexOf(evt.keyCode);
  30082. if (index >= 0) {
  30083. _this._keys.splice(index, 1);
  30084. }
  30085. if (evt.preventDefault) {
  30086. if (!noPreventDefault) {
  30087. evt.preventDefault();
  30088. }
  30089. }
  30090. }
  30091. };
  30092. this._onLostFocus = function () {
  30093. _this._keys = [];
  30094. };
  30095. element.addEventListener("keydown", this._onKeyDown, false);
  30096. element.addEventListener("keyup", this._onKeyUp, false);
  30097. BABYLON.Tools.RegisterTopRootEvents([
  30098. { name: "blur", handler: this._onLostFocus }
  30099. ]);
  30100. };
  30101. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30102. if (element) {
  30103. element.removeEventListener("keydown", this._onKeyDown);
  30104. element.removeEventListener("keyup", this._onKeyUp);
  30105. }
  30106. BABYLON.Tools.UnregisterTopRootEvents([
  30107. { name: "blur", handler: this._onLostFocus }
  30108. ]);
  30109. this._keys = [];
  30110. this._onKeyDown = null;
  30111. this._onKeyUp = null;
  30112. this._onLostFocus = null;
  30113. };
  30114. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30115. if (this._onKeyDown) {
  30116. var camera = this.camera;
  30117. for (var index = 0; index < this._keys.length; index++) {
  30118. var keyCode = this._keys[index];
  30119. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30120. camera.inertialAlphaOffset -= 0.01;
  30121. }
  30122. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30123. camera.inertialBetaOffset -= 0.01;
  30124. }
  30125. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30126. camera.inertialAlphaOffset += 0.01;
  30127. }
  30128. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30129. camera.inertialBetaOffset += 0.01;
  30130. }
  30131. }
  30132. }
  30133. };
  30134. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30135. return "ArcRotateCameraKeyboardMoveInput";
  30136. };
  30137. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30138. return "keyboard";
  30139. };
  30140. return ArcRotateCameraKeyboardMoveInput;
  30141. }());
  30142. __decorate([
  30143. BABYLON.serialize()
  30144. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30145. __decorate([
  30146. BABYLON.serialize()
  30147. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30148. __decorate([
  30149. BABYLON.serialize()
  30150. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30151. __decorate([
  30152. BABYLON.serialize()
  30153. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30154. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30155. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30156. })(BABYLON || (BABYLON = {}));
  30157. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30158. var BABYLON;
  30159. (function (BABYLON) {
  30160. var ArcRotateCameraMouseWheelInput = (function () {
  30161. function ArcRotateCameraMouseWheelInput() {
  30162. this.wheelPrecision = 3.0;
  30163. }
  30164. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30165. var _this = this;
  30166. this._wheel = function (p, s) {
  30167. //sanity check - this should be a PointerWheel event.
  30168. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30169. return;
  30170. var event = p.event;
  30171. var delta = 0;
  30172. if (event.wheelDelta) {
  30173. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30174. }
  30175. else if (event.detail) {
  30176. delta = -event.detail / _this.wheelPrecision;
  30177. }
  30178. if (delta)
  30179. _this.camera.inertialRadiusOffset += delta;
  30180. if (event.preventDefault) {
  30181. if (!noPreventDefault) {
  30182. event.preventDefault();
  30183. }
  30184. }
  30185. };
  30186. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30187. };
  30188. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30189. if (this._observer && element) {
  30190. this.camera.getScene().onPointerObservable.remove(this._observer);
  30191. this._observer = null;
  30192. this._wheel = null;
  30193. }
  30194. };
  30195. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30196. return "ArcRotateCameraMouseWheelInput";
  30197. };
  30198. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30199. return "mousewheel";
  30200. };
  30201. return ArcRotateCameraMouseWheelInput;
  30202. }());
  30203. __decorate([
  30204. BABYLON.serialize()
  30205. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30206. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30207. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30208. })(BABYLON || (BABYLON = {}));
  30209. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30210. var BABYLON;
  30211. (function (BABYLON) {
  30212. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30213. var ArcRotateCameraPointersInput = (function () {
  30214. function ArcRotateCameraPointersInput() {
  30215. this.buttons = [0, 1, 2];
  30216. this.angularSensibilityX = 1000.0;
  30217. this.angularSensibilityY = 1000.0;
  30218. this.pinchPrecision = 6.0;
  30219. this.panningSensibility = 50.0;
  30220. this._isPanClick = false;
  30221. this.pinchInwards = true;
  30222. }
  30223. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30224. var _this = this;
  30225. var engine = this.camera.getEngine();
  30226. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30227. var pointA, pointB;
  30228. var previousPinchDistance = 0;
  30229. this._pointerInput = function (p, s) {
  30230. var evt = p.event;
  30231. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30232. return;
  30233. }
  30234. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30235. try {
  30236. evt.srcElement.setPointerCapture(evt.pointerId);
  30237. }
  30238. catch (e) {
  30239. //Nothing to do with the error. Execution will continue.
  30240. }
  30241. // Manage panning with pan button click
  30242. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30243. // manage pointers
  30244. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30245. if (pointA === undefined) {
  30246. pointA = cacheSoloPointer;
  30247. }
  30248. else if (pointB === undefined) {
  30249. pointB = cacheSoloPointer;
  30250. }
  30251. if (!noPreventDefault) {
  30252. evt.preventDefault();
  30253. element.focus();
  30254. }
  30255. }
  30256. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30257. try {
  30258. evt.srcElement.releasePointerCapture(evt.pointerId);
  30259. }
  30260. catch (e) {
  30261. //Nothing to do with the error.
  30262. }
  30263. cacheSoloPointer = null;
  30264. previousPinchDistance = 0;
  30265. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30266. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30267. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30268. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30269. pointA = pointB = undefined;
  30270. if (!noPreventDefault) {
  30271. evt.preventDefault();
  30272. }
  30273. }
  30274. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30275. if (!noPreventDefault) {
  30276. evt.preventDefault();
  30277. }
  30278. // One button down
  30279. if (pointA && pointB === undefined) {
  30280. if (_this.panningSensibility !== 0 &&
  30281. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30282. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30283. _this.camera
  30284. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30285. _this.camera
  30286. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30287. }
  30288. else {
  30289. var offsetX = evt.clientX - cacheSoloPointer.x;
  30290. var offsetY = evt.clientY - cacheSoloPointer.y;
  30291. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30292. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30293. }
  30294. cacheSoloPointer.x = evt.clientX;
  30295. cacheSoloPointer.y = evt.clientY;
  30296. }
  30297. else if (pointA && pointB) {
  30298. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30299. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30300. ed.x = evt.clientX;
  30301. ed.y = evt.clientY;
  30302. var direction = _this.pinchInwards ? 1 : -1;
  30303. var distX = pointA.x - pointB.x;
  30304. var distY = pointA.y - pointB.y;
  30305. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30306. if (previousPinchDistance === 0) {
  30307. previousPinchDistance = pinchSquaredDistance;
  30308. return;
  30309. }
  30310. if (pinchSquaredDistance !== previousPinchDistance) {
  30311. _this.camera
  30312. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30313. (_this.pinchPrecision *
  30314. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30315. direction);
  30316. previousPinchDistance = pinchSquaredDistance;
  30317. }
  30318. }
  30319. }
  30320. };
  30321. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30322. this._onContextMenu = function (evt) {
  30323. evt.preventDefault();
  30324. };
  30325. if (!this.camera._useCtrlForPanning) {
  30326. element.addEventListener("contextmenu", this._onContextMenu, false);
  30327. }
  30328. this._onLostFocus = function () {
  30329. //this._keys = [];
  30330. pointA = pointB = undefined;
  30331. previousPinchDistance = 0;
  30332. cacheSoloPointer = null;
  30333. };
  30334. this._onMouseMove = function (evt) {
  30335. if (!engine.isPointerLock) {
  30336. return;
  30337. }
  30338. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30339. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30340. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30341. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30342. if (!noPreventDefault) {
  30343. evt.preventDefault();
  30344. }
  30345. };
  30346. this._onGestureStart = function (e) {
  30347. if (window.MSGesture === undefined) {
  30348. return;
  30349. }
  30350. if (!_this._MSGestureHandler) {
  30351. _this._MSGestureHandler = new MSGesture();
  30352. _this._MSGestureHandler.target = element;
  30353. }
  30354. _this._MSGestureHandler.addPointer(e.pointerId);
  30355. };
  30356. this._onGesture = function (e) {
  30357. _this.camera.radius *= e.scale;
  30358. if (e.preventDefault) {
  30359. if (!noPreventDefault) {
  30360. e.stopPropagation();
  30361. e.preventDefault();
  30362. }
  30363. }
  30364. };
  30365. element.addEventListener("mousemove", this._onMouseMove, false);
  30366. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30367. element.addEventListener("MSGestureChange", this._onGesture, false);
  30368. BABYLON.Tools.RegisterTopRootEvents([
  30369. { name: "blur", handler: this._onLostFocus }
  30370. ]);
  30371. };
  30372. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30373. if (element && this._observer) {
  30374. this.camera.getScene().onPointerObservable.remove(this._observer);
  30375. this._observer = null;
  30376. element.removeEventListener("contextmenu", this._onContextMenu);
  30377. element.removeEventListener("mousemove", this._onMouseMove);
  30378. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30379. element.removeEventListener("MSGestureChange", this._onGesture);
  30380. this._isPanClick = false;
  30381. this.pinchInwards = true;
  30382. this._onMouseMove = null;
  30383. this._onGestureStart = null;
  30384. this._onGesture = null;
  30385. this._MSGestureHandler = null;
  30386. this._onLostFocus = null;
  30387. this._onContextMenu = null;
  30388. }
  30389. BABYLON.Tools.UnregisterTopRootEvents([
  30390. { name: "blur", handler: this._onLostFocus }
  30391. ]);
  30392. };
  30393. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30394. return "ArcRotateCameraPointersInput";
  30395. };
  30396. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30397. return "pointers";
  30398. };
  30399. return ArcRotateCameraPointersInput;
  30400. }());
  30401. __decorate([
  30402. BABYLON.serialize()
  30403. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30404. __decorate([
  30405. BABYLON.serialize()
  30406. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30407. __decorate([
  30408. BABYLON.serialize()
  30409. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30410. __decorate([
  30411. BABYLON.serialize()
  30412. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30413. __decorate([
  30414. BABYLON.serialize()
  30415. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30416. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30417. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30418. })(BABYLON || (BABYLON = {}));
  30419. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30420. /// <reference path="babylon.targetCamera.ts" />
  30421. /// <reference path="..\Tools\babylon.tools.ts" />
  30422. var BABYLON;
  30423. (function (BABYLON) {
  30424. var ArcRotateCamera = (function (_super) {
  30425. __extends(ArcRotateCamera, _super);
  30426. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30427. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30428. _this.inertialAlphaOffset = 0;
  30429. _this.inertialBetaOffset = 0;
  30430. _this.inertialRadiusOffset = 0;
  30431. _this.lowerAlphaLimit = null;
  30432. _this.upperAlphaLimit = null;
  30433. _this.lowerBetaLimit = 0.01;
  30434. _this.upperBetaLimit = Math.PI;
  30435. _this.lowerRadiusLimit = null;
  30436. _this.upperRadiusLimit = null;
  30437. _this.inertialPanningX = 0;
  30438. _this.inertialPanningY = 0;
  30439. _this.panningInertia = 0.9;
  30440. //-- end properties for backward compatibility for inputs
  30441. _this.zoomOnFactor = 1;
  30442. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30443. _this.allowUpsideDown = true;
  30444. _this._viewMatrix = new BABYLON.Matrix();
  30445. // Panning
  30446. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30447. _this.checkCollisions = false;
  30448. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30449. _this._previousPosition = BABYLON.Vector3.Zero();
  30450. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30451. _this._newPosition = BABYLON.Vector3.Zero();
  30452. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30453. if (collidedMesh === void 0) { collidedMesh = null; }
  30454. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30455. newPosition.multiplyInPlace(_this._collider.radius);
  30456. }
  30457. if (!collidedMesh) {
  30458. _this._previousPosition.copyFrom(_this.position);
  30459. }
  30460. else {
  30461. _this.setPosition(newPosition);
  30462. if (_this.onCollide) {
  30463. _this.onCollide(collidedMesh);
  30464. }
  30465. }
  30466. // Recompute because of constraints
  30467. var cosa = Math.cos(_this.alpha);
  30468. var sina = Math.sin(_this.alpha);
  30469. var cosb = Math.cos(_this.beta);
  30470. var sinb = Math.sin(_this.beta);
  30471. if (sinb === 0) {
  30472. sinb = 0.0001;
  30473. }
  30474. var target = _this._getTargetPosition();
  30475. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30476. _this.position.copyFrom(_this._newPosition);
  30477. var up = _this.upVector;
  30478. if (_this.allowUpsideDown && _this.beta < 0) {
  30479. up = up.clone();
  30480. up = up.negate();
  30481. }
  30482. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30483. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30484. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30485. _this._collisionTriggered = false;
  30486. };
  30487. _this._target = BABYLON.Vector3.Zero();
  30488. if (target) {
  30489. _this.setTarget(target);
  30490. }
  30491. _this.alpha = alpha;
  30492. _this.beta = beta;
  30493. _this.radius = radius;
  30494. _this.getViewMatrix();
  30495. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30496. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30497. return _this;
  30498. }
  30499. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  30500. get: function () {
  30501. return this._target;
  30502. },
  30503. set: function (value) {
  30504. this.setTarget(value);
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30510. //-- begin properties for backward compatibility for inputs
  30511. get: function () {
  30512. var pointers = this.inputs.attached["pointers"];
  30513. if (pointers)
  30514. return pointers.angularSensibilityX;
  30515. },
  30516. set: function (value) {
  30517. var pointers = this.inputs.attached["pointers"];
  30518. if (pointers) {
  30519. pointers.angularSensibilityX = value;
  30520. }
  30521. },
  30522. enumerable: true,
  30523. configurable: true
  30524. });
  30525. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30526. get: function () {
  30527. var pointers = this.inputs.attached["pointers"];
  30528. if (pointers)
  30529. return pointers.angularSensibilityY;
  30530. },
  30531. set: function (value) {
  30532. var pointers = this.inputs.attached["pointers"];
  30533. if (pointers) {
  30534. pointers.angularSensibilityY = value;
  30535. }
  30536. },
  30537. enumerable: true,
  30538. configurable: true
  30539. });
  30540. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30541. get: function () {
  30542. var pointers = this.inputs.attached["pointers"];
  30543. if (pointers)
  30544. return pointers.pinchPrecision;
  30545. },
  30546. set: function (value) {
  30547. var pointers = this.inputs.attached["pointers"];
  30548. if (pointers) {
  30549. pointers.pinchPrecision = value;
  30550. }
  30551. },
  30552. enumerable: true,
  30553. configurable: true
  30554. });
  30555. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30556. get: function () {
  30557. var pointers = this.inputs.attached["pointers"];
  30558. if (pointers)
  30559. return pointers.panningSensibility;
  30560. },
  30561. set: function (value) {
  30562. var pointers = this.inputs.attached["pointers"];
  30563. if (pointers) {
  30564. pointers.panningSensibility = value;
  30565. }
  30566. },
  30567. enumerable: true,
  30568. configurable: true
  30569. });
  30570. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30571. get: function () {
  30572. var keyboard = this.inputs.attached["keyboard"];
  30573. if (keyboard)
  30574. return keyboard.keysUp;
  30575. },
  30576. set: function (value) {
  30577. var keyboard = this.inputs.attached["keyboard"];
  30578. if (keyboard)
  30579. keyboard.keysUp = value;
  30580. },
  30581. enumerable: true,
  30582. configurable: true
  30583. });
  30584. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30585. get: function () {
  30586. var keyboard = this.inputs.attached["keyboard"];
  30587. if (keyboard)
  30588. return keyboard.keysDown;
  30589. },
  30590. set: function (value) {
  30591. var keyboard = this.inputs.attached["keyboard"];
  30592. if (keyboard)
  30593. keyboard.keysDown = value;
  30594. },
  30595. enumerable: true,
  30596. configurable: true
  30597. });
  30598. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30599. get: function () {
  30600. var keyboard = this.inputs.attached["keyboard"];
  30601. if (keyboard)
  30602. return keyboard.keysLeft;
  30603. },
  30604. set: function (value) {
  30605. var keyboard = this.inputs.attached["keyboard"];
  30606. if (keyboard)
  30607. keyboard.keysLeft = value;
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30613. get: function () {
  30614. var keyboard = this.inputs.attached["keyboard"];
  30615. if (keyboard)
  30616. return keyboard.keysRight;
  30617. },
  30618. set: function (value) {
  30619. var keyboard = this.inputs.attached["keyboard"];
  30620. if (keyboard)
  30621. keyboard.keysRight = value;
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30627. get: function () {
  30628. var mousewheel = this.inputs.attached["mousewheel"];
  30629. if (mousewheel)
  30630. return mousewheel.wheelPrecision;
  30631. },
  30632. set: function (value) {
  30633. var mousewheel = this.inputs.attached["mousewheel"];
  30634. if (mousewheel)
  30635. mousewheel.wheelPrecision = value;
  30636. },
  30637. enumerable: true,
  30638. configurable: true
  30639. });
  30640. // Cache
  30641. ArcRotateCamera.prototype._initCache = function () {
  30642. _super.prototype._initCache.call(this);
  30643. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30644. this._cache.alpha = undefined;
  30645. this._cache.beta = undefined;
  30646. this._cache.radius = undefined;
  30647. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30648. };
  30649. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30650. if (!ignoreParentClass) {
  30651. _super.prototype._updateCache.call(this);
  30652. }
  30653. this._cache._target.copyFrom(this._getTargetPosition());
  30654. this._cache.alpha = this.alpha;
  30655. this._cache.beta = this.beta;
  30656. this._cache.radius = this.radius;
  30657. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30658. };
  30659. ArcRotateCamera.prototype._getTargetPosition = function () {
  30660. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  30661. var pos = this._targetHost.getAbsolutePosition();
  30662. if (this._targetBoundingCenter) {
  30663. pos.addToRef(this._targetBoundingCenter, this._target);
  30664. }
  30665. else {
  30666. this._target.copyFrom(pos);
  30667. }
  30668. }
  30669. var lockedTargetPosition = this._getLockedTargetPosition();
  30670. if (lockedTargetPosition) {
  30671. return lockedTargetPosition;
  30672. }
  30673. return this._target;
  30674. };
  30675. // Synchronized
  30676. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30677. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30678. return false;
  30679. return this._cache._target.equals(this._getTargetPosition())
  30680. && this._cache.alpha === this.alpha
  30681. && this._cache.beta === this.beta
  30682. && this._cache.radius === this.radius
  30683. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30684. };
  30685. // Methods
  30686. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30687. var _this = this;
  30688. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30689. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30690. this._useCtrlForPanning = useCtrlForPanning;
  30691. this._panningMouseButton = panningMouseButton;
  30692. this.inputs.attachElement(element, noPreventDefault);
  30693. this._reset = function () {
  30694. _this.inertialAlphaOffset = 0;
  30695. _this.inertialBetaOffset = 0;
  30696. _this.inertialRadiusOffset = 0;
  30697. };
  30698. };
  30699. ArcRotateCamera.prototype.detachControl = function (element) {
  30700. this.inputs.detachElement(element);
  30701. if (this._reset) {
  30702. this._reset();
  30703. }
  30704. };
  30705. ArcRotateCamera.prototype._checkInputs = function () {
  30706. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30707. if (this._collisionTriggered) {
  30708. return;
  30709. }
  30710. this.inputs.checkInputs();
  30711. // Inertia
  30712. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30713. if (this.getScene().useRightHandedSystem) {
  30714. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30715. }
  30716. else {
  30717. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30718. }
  30719. this.beta += this.inertialBetaOffset;
  30720. this.radius -= this.inertialRadiusOffset;
  30721. this.inertialAlphaOffset *= this.inertia;
  30722. this.inertialBetaOffset *= this.inertia;
  30723. this.inertialRadiusOffset *= this.inertia;
  30724. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  30725. this.inertialAlphaOffset = 0;
  30726. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  30727. this.inertialBetaOffset = 0;
  30728. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  30729. this.inertialRadiusOffset = 0;
  30730. }
  30731. // Panning inertia
  30732. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30733. if (!this._localDirection) {
  30734. this._localDirection = BABYLON.Vector3.Zero();
  30735. this._transformedDirection = BABYLON.Vector3.Zero();
  30736. }
  30737. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30738. this._localDirection.multiplyInPlace(this.panningAxis);
  30739. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30740. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30741. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30742. if (!this.panningAxis.y) {
  30743. this._transformedDirection.y = 0;
  30744. }
  30745. if (!this._targetHost) {
  30746. this._target.addInPlace(this._transformedDirection);
  30747. }
  30748. this.inertialPanningX *= this.panningInertia;
  30749. this.inertialPanningY *= this.panningInertia;
  30750. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  30751. this.inertialPanningX = 0;
  30752. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  30753. this.inertialPanningY = 0;
  30754. }
  30755. // Limits
  30756. this._checkLimits();
  30757. _super.prototype._checkInputs.call(this);
  30758. };
  30759. ArcRotateCamera.prototype._checkLimits = function () {
  30760. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30761. if (this.allowUpsideDown && this.beta > Math.PI) {
  30762. this.beta = this.beta - (2 * Math.PI);
  30763. }
  30764. }
  30765. else {
  30766. if (this.beta < this.lowerBetaLimit) {
  30767. this.beta = this.lowerBetaLimit;
  30768. }
  30769. }
  30770. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30771. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30772. this.beta = this.beta + (2 * Math.PI);
  30773. }
  30774. }
  30775. else {
  30776. if (this.beta > this.upperBetaLimit) {
  30777. this.beta = this.upperBetaLimit;
  30778. }
  30779. }
  30780. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30781. this.alpha = this.lowerAlphaLimit;
  30782. }
  30783. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30784. this.alpha = this.upperAlphaLimit;
  30785. }
  30786. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30787. this.radius = this.lowerRadiusLimit;
  30788. }
  30789. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30790. this.radius = this.upperRadiusLimit;
  30791. }
  30792. };
  30793. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30794. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30795. this.radius = radiusv3.length();
  30796. // Alpha
  30797. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30798. if (radiusv3.z < 0) {
  30799. this.alpha = 2 * Math.PI - this.alpha;
  30800. }
  30801. // Beta
  30802. this.beta = Math.acos(radiusv3.y / this.radius);
  30803. this._checkLimits();
  30804. };
  30805. ArcRotateCamera.prototype.setPosition = function (position) {
  30806. if (this.position.equals(position)) {
  30807. return;
  30808. }
  30809. this.position.copyFrom(position);
  30810. this.rebuildAnglesAndRadius();
  30811. };
  30812. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30813. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30814. if (allowSamePosition === void 0) { allowSamePosition = false; }
  30815. if (target.getBoundingInfo) {
  30816. if (toBoundingCenter) {
  30817. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  30818. }
  30819. else {
  30820. this._targetBoundingCenter = null;
  30821. }
  30822. this._targetHost = target;
  30823. this._target = this._getTargetPosition();
  30824. }
  30825. else {
  30826. var newTarget = target;
  30827. var currentTarget = this._getTargetPosition();
  30828. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  30829. return;
  30830. }
  30831. this._target = newTarget;
  30832. this._targetBoundingCenter = null;
  30833. }
  30834. this.rebuildAnglesAndRadius();
  30835. };
  30836. ArcRotateCamera.prototype._getViewMatrix = function () {
  30837. // Compute
  30838. var cosa = Math.cos(this.alpha);
  30839. var sina = Math.sin(this.alpha);
  30840. var cosb = Math.cos(this.beta);
  30841. var sinb = Math.sin(this.beta);
  30842. if (sinb === 0) {
  30843. sinb = 0.0001;
  30844. }
  30845. var target = this._getTargetPosition();
  30846. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  30847. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  30848. if (!this._collider) {
  30849. this._collider = new BABYLON.Collider();
  30850. }
  30851. this._collider.radius = this.collisionRadius;
  30852. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  30853. this._collisionTriggered = true;
  30854. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30855. }
  30856. else {
  30857. this.position.copyFrom(this._newPosition);
  30858. var up = this.upVector;
  30859. if (this.allowUpsideDown && sinb < 0) {
  30860. up = up.clone();
  30861. up = up.negate();
  30862. }
  30863. if (this.getScene().useRightHandedSystem) {
  30864. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  30865. }
  30866. else {
  30867. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  30868. }
  30869. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  30870. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  30871. }
  30872. this._currentTarget = target;
  30873. return this._viewMatrix;
  30874. };
  30875. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  30876. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30877. meshes = meshes || this.getScene().meshes;
  30878. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  30879. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  30880. this.radius = distance * this.zoomOnFactor;
  30881. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  30882. };
  30883. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  30884. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30885. var meshesOrMinMaxVector;
  30886. var distance;
  30887. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  30888. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  30889. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  30890. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  30891. }
  30892. else {
  30893. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  30894. distance = meshesOrMinMaxVectorAndDistance.distance;
  30895. }
  30896. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  30897. if (!doNotUpdateMaxZ) {
  30898. this.maxZ = distance * 2;
  30899. }
  30900. };
  30901. /**
  30902. * @override
  30903. * Override Camera.createRigCamera
  30904. */
  30905. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30906. var alphaShift;
  30907. switch (this.cameraRigMode) {
  30908. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30910. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30911. case BABYLON.Camera.RIG_MODE_VR:
  30912. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  30913. break;
  30914. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30915. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  30916. break;
  30917. }
  30918. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  30919. rigCam._cameraRigParams = {};
  30920. return rigCam;
  30921. };
  30922. /**
  30923. * @override
  30924. * Override Camera._updateRigCameras
  30925. */
  30926. ArcRotateCamera.prototype._updateRigCameras = function () {
  30927. var camLeft = this._rigCameras[0];
  30928. var camRight = this._rigCameras[1];
  30929. camLeft.beta = camRight.beta = this.beta;
  30930. camLeft.radius = camRight.radius = this.radius;
  30931. switch (this.cameraRigMode) {
  30932. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30933. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30934. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30935. case BABYLON.Camera.RIG_MODE_VR:
  30936. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30937. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30938. break;
  30939. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30940. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30941. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30942. break;
  30943. }
  30944. _super.prototype._updateRigCameras.call(this);
  30945. };
  30946. ArcRotateCamera.prototype.dispose = function () {
  30947. this.inputs.clear();
  30948. _super.prototype.dispose.call(this);
  30949. };
  30950. ArcRotateCamera.prototype.getClassName = function () {
  30951. return "ArcRotateCamera";
  30952. };
  30953. return ArcRotateCamera;
  30954. }(BABYLON.TargetCamera));
  30955. __decorate([
  30956. BABYLON.serialize()
  30957. ], ArcRotateCamera.prototype, "alpha", void 0);
  30958. __decorate([
  30959. BABYLON.serialize()
  30960. ], ArcRotateCamera.prototype, "beta", void 0);
  30961. __decorate([
  30962. BABYLON.serialize()
  30963. ], ArcRotateCamera.prototype, "radius", void 0);
  30964. __decorate([
  30965. BABYLON.serializeAsVector3("target")
  30966. ], ArcRotateCamera.prototype, "_target", void 0);
  30967. __decorate([
  30968. BABYLON.serialize()
  30969. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  30970. __decorate([
  30971. BABYLON.serialize()
  30972. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  30973. __decorate([
  30974. BABYLON.serialize()
  30975. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  30976. __decorate([
  30977. BABYLON.serialize()
  30978. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  30979. __decorate([
  30980. BABYLON.serialize()
  30981. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  30982. __decorate([
  30983. BABYLON.serialize()
  30984. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  30985. __decorate([
  30986. BABYLON.serialize()
  30987. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  30988. __decorate([
  30989. BABYLON.serialize()
  30990. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  30991. __decorate([
  30992. BABYLON.serialize()
  30993. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  30994. __decorate([
  30995. BABYLON.serialize()
  30996. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  30997. __decorate([
  30998. BABYLON.serialize()
  30999. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  31000. __decorate([
  31001. BABYLON.serialize()
  31002. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  31003. __decorate([
  31004. BABYLON.serialize()
  31005. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  31006. __decorate([
  31007. BABYLON.serialize()
  31008. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  31009. BABYLON.ArcRotateCamera = ArcRotateCamera;
  31010. })(BABYLON || (BABYLON = {}));
  31011. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  31012. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  31013. var BABYLON;
  31014. (function (BABYLON) {
  31015. var ArcRotateCameraInputsManager = (function (_super) {
  31016. __extends(ArcRotateCameraInputsManager, _super);
  31017. function ArcRotateCameraInputsManager(camera) {
  31018. return _super.call(this, camera) || this;
  31019. }
  31020. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31021. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31022. return this;
  31023. };
  31024. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31025. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31026. return this;
  31027. };
  31028. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31029. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31030. return this;
  31031. };
  31032. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31033. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31034. return this;
  31035. };
  31036. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31037. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31038. return this;
  31039. };
  31040. return ArcRotateCameraInputsManager;
  31041. }(BABYLON.CameraInputsManager));
  31042. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31043. })(BABYLON || (BABYLON = {}));
  31044. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31045. var BABYLON;
  31046. (function (BABYLON) {
  31047. var CubeTexture = (function (_super) {
  31048. __extends(CubeTexture, _super);
  31049. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  31050. if (onLoad === void 0) { onLoad = null; }
  31051. if (onError === void 0) { onError = null; }
  31052. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31053. var _this = _super.call(this, scene) || this;
  31054. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  31055. _this.name = rootUrl;
  31056. _this.url = rootUrl;
  31057. _this._noMipmap = noMipmap;
  31058. _this.hasAlpha = false;
  31059. _this._format = format;
  31060. if (!rootUrl && !files) {
  31061. return _this;
  31062. }
  31063. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  31064. if (!files) {
  31065. if (!extensions) {
  31066. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  31067. }
  31068. files = [];
  31069. for (var index = 0; index < extensions.length; index++) {
  31070. files.push(rootUrl + extensions[index]);
  31071. }
  31072. _this._extensions = extensions;
  31073. }
  31074. _this._files = files;
  31075. if (!_this._texture) {
  31076. if (!scene.useDelayedTextureLoading) {
  31077. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  31078. }
  31079. else {
  31080. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31081. }
  31082. }
  31083. else if (onLoad) {
  31084. if (_this._texture.isReady) {
  31085. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  31086. }
  31087. else {
  31088. _this._texture.onLoadedCallbacks.push(onLoad);
  31089. }
  31090. }
  31091. _this.isCube = true;
  31092. _this._textureMatrix = BABYLON.Matrix.Identity();
  31093. return _this;
  31094. }
  31095. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  31096. return new CubeTexture("", scene, null, noMipmap, files);
  31097. };
  31098. // Methods
  31099. CubeTexture.prototype.delayLoad = function () {
  31100. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31101. return;
  31102. }
  31103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31104. this._texture = this._getFromCache(this.url, this._noMipmap);
  31105. if (!this._texture) {
  31106. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  31107. }
  31108. };
  31109. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  31110. return this._textureMatrix;
  31111. };
  31112. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31113. var texture = BABYLON.SerializationHelper.Parse(function () {
  31114. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  31115. }, parsedTexture, scene);
  31116. // Animations
  31117. if (parsedTexture.animations) {
  31118. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31119. var parsedAnimation = parsedTexture.animations[animationIndex];
  31120. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31121. }
  31122. }
  31123. return texture;
  31124. };
  31125. CubeTexture.prototype.clone = function () {
  31126. var _this = this;
  31127. return BABYLON.SerializationHelper.Clone(function () {
  31128. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  31129. }, this);
  31130. };
  31131. return CubeTexture;
  31132. }(BABYLON.BaseTexture));
  31133. BABYLON.CubeTexture = CubeTexture;
  31134. })(BABYLON || (BABYLON = {}));
  31135. //# sourceMappingURL=babylon.cubeTexture.js.map
  31136. var BABYLON;
  31137. (function (BABYLON) {
  31138. var RenderTargetTexture = (function (_super) {
  31139. __extends(RenderTargetTexture, _super);
  31140. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  31141. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  31142. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31143. if (isCube === void 0) { isCube = false; }
  31144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31145. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31146. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  31147. if (isMulti === void 0) { isMulti = false; }
  31148. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  31149. _this.isCube = isCube;
  31150. /**
  31151. * Use this list to define the list of mesh you want to render.
  31152. */
  31153. _this.renderList = new Array();
  31154. _this.renderParticles = true;
  31155. _this.renderSprites = false;
  31156. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  31157. // Events
  31158. /**
  31159. * An event triggered when the texture is unbind.
  31160. * @type {BABYLON.Observable}
  31161. */
  31162. _this.onAfterUnbindObservable = new BABYLON.Observable();
  31163. /**
  31164. * An event triggered before rendering the texture
  31165. * @type {BABYLON.Observable}
  31166. */
  31167. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31168. /**
  31169. * An event triggered after rendering the texture
  31170. * @type {BABYLON.Observable}
  31171. */
  31172. _this.onAfterRenderObservable = new BABYLON.Observable();
  31173. /**
  31174. * An event triggered after the texture clear
  31175. * @type {BABYLON.Observable}
  31176. */
  31177. _this.onClearObservable = new BABYLON.Observable();
  31178. _this._currentRefreshId = -1;
  31179. _this._refreshRate = 1;
  31180. _this._samples = 1;
  31181. scene = _this.getScene();
  31182. _this.name = name;
  31183. _this.isRenderTarget = true;
  31184. _this._size = size;
  31185. _this._generateMipMaps = generateMipMaps;
  31186. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  31187. // Rendering groups
  31188. _this._renderingManager = new BABYLON.RenderingManager(scene);
  31189. if (isMulti) {
  31190. return _this;
  31191. }
  31192. _this._renderTargetOptions = {
  31193. generateMipMaps: generateMipMaps,
  31194. type: type,
  31195. samplingMode: samplingMode,
  31196. generateDepthBuffer: generateDepthBuffer,
  31197. generateStencilBuffer: generateStencilBuffer
  31198. };
  31199. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31200. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31201. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31202. }
  31203. if (isCube) {
  31204. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  31205. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  31206. _this._textureMatrix = BABYLON.Matrix.Identity();
  31207. }
  31208. else {
  31209. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  31210. }
  31211. return _this;
  31212. }
  31213. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  31214. get: function () {
  31215. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  31216. },
  31217. enumerable: true,
  31218. configurable: true
  31219. });
  31220. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  31221. get: function () {
  31222. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  31223. },
  31224. enumerable: true,
  31225. configurable: true
  31226. });
  31227. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  31228. get: function () {
  31229. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  31230. },
  31231. enumerable: true,
  31232. configurable: true
  31233. });
  31234. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  31235. set: function (callback) {
  31236. if (this._onAfterUnbindObserver) {
  31237. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  31238. }
  31239. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  31240. },
  31241. enumerable: true,
  31242. configurable: true
  31243. });
  31244. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  31245. set: function (callback) {
  31246. if (this._onBeforeRenderObserver) {
  31247. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31248. }
  31249. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31250. },
  31251. enumerable: true,
  31252. configurable: true
  31253. });
  31254. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  31255. set: function (callback) {
  31256. if (this._onAfterRenderObserver) {
  31257. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31258. }
  31259. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  31265. set: function (callback) {
  31266. if (this._onClearObserver) {
  31267. this.onClearObservable.remove(this._onClearObserver);
  31268. }
  31269. this._onClearObserver = this.onClearObservable.add(callback);
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  31275. get: function () {
  31276. return this._renderTargetOptions;
  31277. },
  31278. enumerable: true,
  31279. configurable: true
  31280. });
  31281. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  31282. get: function () {
  31283. return this._samples;
  31284. },
  31285. set: function (value) {
  31286. if (this._samples === value) {
  31287. return;
  31288. }
  31289. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  31290. },
  31291. enumerable: true,
  31292. configurable: true
  31293. });
  31294. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  31295. this._currentRefreshId = -1;
  31296. };
  31297. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  31298. get: function () {
  31299. return this._refreshRate;
  31300. },
  31301. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  31302. set: function (value) {
  31303. this._refreshRate = value;
  31304. this.resetRefreshCounter();
  31305. },
  31306. enumerable: true,
  31307. configurable: true
  31308. });
  31309. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  31310. if (!this._postProcessManager) {
  31311. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  31312. this._postProcesses = new Array();
  31313. }
  31314. this._postProcesses.push(postProcess);
  31315. this._postProcesses[0].autoClear = false;
  31316. };
  31317. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  31318. if (!this._postProcesses) {
  31319. return;
  31320. }
  31321. if (dispose) {
  31322. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  31323. var postProcess = _a[_i];
  31324. postProcess.dispose();
  31325. postProcess = null;
  31326. }
  31327. }
  31328. this._postProcesses = [];
  31329. };
  31330. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  31331. if (!this._postProcesses) {
  31332. return;
  31333. }
  31334. var index = this._postProcesses.indexOf(postProcess);
  31335. if (index === -1) {
  31336. return;
  31337. }
  31338. this._postProcesses.splice(index, 1);
  31339. if (this._postProcesses.length > 0) {
  31340. this._postProcesses[0].autoClear = false;
  31341. }
  31342. };
  31343. RenderTargetTexture.prototype._shouldRender = function () {
  31344. if (this._currentRefreshId === -1) {
  31345. this._currentRefreshId = 1;
  31346. return true;
  31347. }
  31348. if (this.refreshRate === this._currentRefreshId) {
  31349. this._currentRefreshId = 1;
  31350. return true;
  31351. }
  31352. this._currentRefreshId++;
  31353. return false;
  31354. };
  31355. RenderTargetTexture.prototype.isReady = function () {
  31356. if (!this.getScene().renderTargetsEnabled) {
  31357. return false;
  31358. }
  31359. return _super.prototype.isReady.call(this);
  31360. };
  31361. RenderTargetTexture.prototype.getRenderSize = function () {
  31362. return this._size;
  31363. };
  31364. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  31365. get: function () {
  31366. return true;
  31367. },
  31368. enumerable: true,
  31369. configurable: true
  31370. });
  31371. RenderTargetTexture.prototype.scale = function (ratio) {
  31372. var newSize = this._size * ratio;
  31373. this.resize(newSize);
  31374. };
  31375. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  31376. if (this.isCube) {
  31377. return this._textureMatrix;
  31378. }
  31379. return _super.prototype.getReflectionTextureMatrix.call(this);
  31380. };
  31381. RenderTargetTexture.prototype.resize = function (size) {
  31382. this.releaseInternalTexture();
  31383. if (this.isCube) {
  31384. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  31385. }
  31386. else {
  31387. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  31388. }
  31389. };
  31390. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  31391. var scene = this.getScene();
  31392. var engine = scene.getEngine();
  31393. if (this.useCameraPostProcesses !== undefined) {
  31394. useCameraPostProcess = this.useCameraPostProcesses;
  31395. }
  31396. if (this._waitingRenderList) {
  31397. this.renderList = [];
  31398. for (var index = 0; index < this._waitingRenderList.length; index++) {
  31399. var id = this._waitingRenderList[index];
  31400. this.renderList.push(scene.getMeshByID(id));
  31401. }
  31402. delete this._waitingRenderList;
  31403. }
  31404. // Is predicate defined?
  31405. if (this.renderListPredicate) {
  31406. this.renderList.splice(0); // Clear previous renderList
  31407. var sceneMeshes = this.getScene().meshes;
  31408. for (var index = 0; index < sceneMeshes.length; index++) {
  31409. var mesh = sceneMeshes[index];
  31410. if (this.renderListPredicate(mesh)) {
  31411. this.renderList.push(mesh);
  31412. }
  31413. }
  31414. }
  31415. if (this.renderList && this.renderList.length === 0) {
  31416. return;
  31417. }
  31418. // Set custom projection.
  31419. // Needs to be before binding to prevent changing the aspect ratio.
  31420. var camera;
  31421. if (this.activeCamera) {
  31422. camera = this.activeCamera;
  31423. engine.setViewport(this.activeCamera.viewport);
  31424. if (this.activeCamera !== scene.activeCamera) {
  31425. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  31426. }
  31427. }
  31428. else {
  31429. camera = scene.activeCamera;
  31430. engine.setViewport(scene.activeCamera.viewport);
  31431. }
  31432. // Prepare renderingManager
  31433. this._renderingManager.reset();
  31434. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  31435. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  31436. var sceneRenderId = scene.getRenderId();
  31437. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  31438. var mesh = currentRenderList[meshIndex];
  31439. if (mesh) {
  31440. if (!mesh.isReady()) {
  31441. // Reset _currentRefreshId
  31442. this.resetRefreshCounter();
  31443. continue;
  31444. }
  31445. mesh._preActivateForIntermediateRendering(sceneRenderId);
  31446. var isMasked = void 0;
  31447. if (!this.renderList) {
  31448. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  31449. }
  31450. else {
  31451. isMasked = false;
  31452. }
  31453. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  31454. mesh._activate(sceneRenderId);
  31455. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31456. var subMesh = mesh.subMeshes[subIndex];
  31457. scene._activeIndices.addCount(subMesh.indexCount, false);
  31458. this._renderingManager.dispatch(subMesh);
  31459. }
  31460. }
  31461. }
  31462. }
  31463. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  31464. var particleSystem = scene.particleSystems[particleIndex];
  31465. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  31466. continue;
  31467. }
  31468. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  31469. this._renderingManager.dispatchParticles(particleSystem);
  31470. }
  31471. }
  31472. if (this.isCube) {
  31473. for (var face = 0; face < 6; face++) {
  31474. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31475. scene.incrementRenderId();
  31476. scene.resetCachedMaterial();
  31477. }
  31478. }
  31479. else {
  31480. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31481. }
  31482. this.onAfterUnbindObservable.notifyObservers(this);
  31483. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  31484. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  31485. }
  31486. engine.setViewport(scene.activeCamera.viewport);
  31487. scene.resetCachedMaterial();
  31488. };
  31489. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  31490. var _this = this;
  31491. var scene = this.getScene();
  31492. var engine = scene.getEngine();
  31493. // Bind
  31494. if (this._postProcessManager) {
  31495. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  31496. }
  31497. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  31498. if (this.isCube) {
  31499. engine.bindFramebuffer(this._texture, faceIndex);
  31500. }
  31501. else {
  31502. engine.bindFramebuffer(this._texture);
  31503. }
  31504. }
  31505. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  31506. // Clear
  31507. if (this.onClearObservable.hasObservers()) {
  31508. this.onClearObservable.notifyObservers(engine);
  31509. }
  31510. else {
  31511. engine.clear(scene.clearColor, true, true, true);
  31512. }
  31513. if (!this._doNotChangeAspectRatio) {
  31514. scene.updateTransformMatrix(true);
  31515. }
  31516. // Render
  31517. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  31518. if (this._postProcessManager) {
  31519. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  31520. }
  31521. else if (useCameraPostProcess) {
  31522. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  31523. }
  31524. if (!this._doNotChangeAspectRatio) {
  31525. scene.updateTransformMatrix(true);
  31526. }
  31527. // Dump ?
  31528. if (dumpForDebug) {
  31529. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  31530. }
  31531. // Unbind
  31532. if (!this.isCube || faceIndex === 5) {
  31533. if (this.isCube) {
  31534. if (faceIndex === 5) {
  31535. engine.generateMipMapsForCubemap(this._texture);
  31536. }
  31537. }
  31538. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  31539. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  31540. });
  31541. }
  31542. else {
  31543. this.onAfterRenderObservable.notifyObservers(faceIndex);
  31544. }
  31545. };
  31546. /**
  31547. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  31548. * This allowed control for front to back rendering or reversly depending of the special needs.
  31549. *
  31550. * @param renderingGroupId The rendering group id corresponding to its index
  31551. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  31552. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  31553. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  31554. */
  31555. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  31556. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  31557. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  31558. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  31559. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  31560. };
  31561. /**
  31562. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  31563. *
  31564. * @param renderingGroupId The rendering group id corresponding to its index
  31565. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  31566. */
  31567. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  31568. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  31569. };
  31570. RenderTargetTexture.prototype.clone = function () {
  31571. var textureSize = this.getSize();
  31572. 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);
  31573. // Base texture
  31574. newTexture.hasAlpha = this.hasAlpha;
  31575. newTexture.level = this.level;
  31576. // RenderTarget Texture
  31577. newTexture.coordinatesMode = this.coordinatesMode;
  31578. newTexture.renderList = this.renderList.slice(0);
  31579. return newTexture;
  31580. };
  31581. RenderTargetTexture.prototype.serialize = function () {
  31582. if (!this.name) {
  31583. return null;
  31584. }
  31585. var serializationObject = _super.prototype.serialize.call(this);
  31586. serializationObject.renderTargetSize = this.getRenderSize();
  31587. serializationObject.renderList = [];
  31588. for (var index = 0; index < this.renderList.length; index++) {
  31589. serializationObject.renderList.push(this.renderList[index].id);
  31590. }
  31591. return serializationObject;
  31592. };
  31593. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  31594. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  31595. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  31596. };
  31597. RenderTargetTexture.prototype.dispose = function () {
  31598. if (this._postProcessManager) {
  31599. this._postProcessManager.dispose();
  31600. this._postProcessManager = null;
  31601. }
  31602. this.clearPostProcesses(true);
  31603. // Remove from custom render targets
  31604. var scene = this.getScene();
  31605. var index = scene.customRenderTargets.indexOf(this);
  31606. if (index >= 0) {
  31607. scene.customRenderTargets.splice(index, 1);
  31608. }
  31609. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  31610. var camera = _a[_i];
  31611. index = camera.customRenderTargets.indexOf(this);
  31612. if (index >= 0) {
  31613. camera.customRenderTargets.splice(index, 1);
  31614. }
  31615. }
  31616. _super.prototype.dispose.call(this);
  31617. };
  31618. return RenderTargetTexture;
  31619. }(BABYLON.Texture));
  31620. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  31621. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  31622. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  31623. BABYLON.RenderTargetTexture = RenderTargetTexture;
  31624. })(BABYLON || (BABYLON = {}));
  31625. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  31626. var BABYLON;
  31627. (function (BABYLON) {
  31628. ;
  31629. var MultiRenderTarget = (function (_super) {
  31630. __extends(MultiRenderTarget, _super);
  31631. function MultiRenderTarget(name, size, count, scene, options) {
  31632. var _this = this;
  31633. options = options || {};
  31634. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  31635. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  31636. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  31637. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  31638. if (!_this.isSupported) {
  31639. _this.dispose();
  31640. return;
  31641. }
  31642. var types = [];
  31643. var samplingModes = [];
  31644. for (var i = 0; i < count; i++) {
  31645. if (options.types && options.types[i]) {
  31646. types.push(options.types[i]);
  31647. }
  31648. else {
  31649. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  31650. }
  31651. if (options.samplingModes && options.samplingModes[i]) {
  31652. samplingModes.push(options.samplingModes[i]);
  31653. }
  31654. else {
  31655. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31656. }
  31657. }
  31658. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  31659. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  31660. _this._count = count;
  31661. _this._size = size;
  31662. _this._multiRenderTargetOptions = {
  31663. samplingModes: samplingModes,
  31664. generateMipMaps: generateMipMaps,
  31665. generateDepthBuffer: generateDepthBuffer,
  31666. generateStencilBuffer: generateStencilBuffer,
  31667. generateDepthTexture: generateDepthTexture,
  31668. types: types,
  31669. textureCount: count
  31670. };
  31671. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  31672. _this._createInternalTextures();
  31673. return _this;
  31674. }
  31675. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  31676. get: function () {
  31677. var engine = this.getScene().getEngine();
  31678. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  31679. },
  31680. enumerable: true,
  31681. configurable: true
  31682. });
  31683. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  31684. get: function () {
  31685. return this._textures;
  31686. },
  31687. enumerable: true,
  31688. configurable: true
  31689. });
  31690. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  31691. get: function () {
  31692. return this._textures[this._textures.length - 1];
  31693. },
  31694. enumerable: true,
  31695. configurable: true
  31696. });
  31697. MultiRenderTarget.prototype._createInternalTextures = function () {
  31698. this._textures = [];
  31699. for (var i = 0; i < this._webGLTextures.length; i++) {
  31700. var texture = new BABYLON.Texture(null, this.getScene());
  31701. texture._texture = this._webGLTextures[i];
  31702. this._textures.push(texture);
  31703. }
  31704. // Keeps references to frame buffer and stencil/depth buffer
  31705. this._texture = this._webGLTextures[0];
  31706. };
  31707. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  31708. get: function () {
  31709. return this._samples;
  31710. },
  31711. set: function (value) {
  31712. if (this._samples === value) {
  31713. return;
  31714. }
  31715. for (var i = 0; i < this._webGLTextures.length; i++) {
  31716. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  31717. }
  31718. },
  31719. enumerable: true,
  31720. configurable: true
  31721. });
  31722. MultiRenderTarget.prototype.resize = function (size) {
  31723. this.releaseInternalTextures();
  31724. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  31725. this._createInternalTextures();
  31726. };
  31727. MultiRenderTarget.prototype.dispose = function () {
  31728. this.releaseInternalTextures();
  31729. _super.prototype.dispose.call(this);
  31730. };
  31731. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  31732. if (!this._webGLTextures) {
  31733. return;
  31734. }
  31735. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  31736. if (this._webGLTextures[i] !== undefined) {
  31737. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  31738. this._webGLTextures.splice(i, 1);
  31739. }
  31740. }
  31741. };
  31742. return MultiRenderTarget;
  31743. }(BABYLON.RenderTargetTexture));
  31744. BABYLON.MultiRenderTarget = MultiRenderTarget;
  31745. })(BABYLON || (BABYLON = {}));
  31746. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  31747. /// <reference path="babylon.renderTargetTexture.ts" />
  31748. var BABYLON;
  31749. (function (BABYLON) {
  31750. var MirrorTexture = (function (_super) {
  31751. __extends(MirrorTexture, _super);
  31752. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  31753. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31755. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31756. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  31757. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  31758. _this._transformMatrix = BABYLON.Matrix.Zero();
  31759. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  31760. _this._blurKernelX = 0;
  31761. _this._blurKernelY = 0;
  31762. _this._blurRatio = 1.0;
  31763. _this.onBeforeRenderObservable.add(function () {
  31764. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  31765. _this._savedViewMatrix = scene.getViewMatrix();
  31766. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  31767. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  31768. scene.clipPlane = _this.mirrorPlane;
  31769. scene.getEngine().cullBackFaces = false;
  31770. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  31771. });
  31772. _this.onAfterRenderObservable.add(function () {
  31773. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  31774. scene.getEngine().cullBackFaces = true;
  31775. scene._mirroredCameraPosition = null;
  31776. delete scene.clipPlane;
  31777. });
  31778. return _this;
  31779. }
  31780. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  31781. get: function () {
  31782. return this._blurRatio;
  31783. },
  31784. set: function (value) {
  31785. if (this._blurRatio === value) {
  31786. return;
  31787. }
  31788. this._blurRatio = value;
  31789. this._preparePostProcesses();
  31790. },
  31791. enumerable: true,
  31792. configurable: true
  31793. });
  31794. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  31795. set: function (value) {
  31796. this.blurKernelX = value;
  31797. this.blurKernelY = value;
  31798. },
  31799. enumerable: true,
  31800. configurable: true
  31801. });
  31802. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  31803. get: function () {
  31804. return this._blurKernelX;
  31805. },
  31806. set: function (value) {
  31807. if (this._blurKernelX === value) {
  31808. return;
  31809. }
  31810. this._blurKernelX = value;
  31811. this._preparePostProcesses();
  31812. },
  31813. enumerable: true,
  31814. configurable: true
  31815. });
  31816. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  31817. get: function () {
  31818. return this._blurKernelY;
  31819. },
  31820. set: function (value) {
  31821. if (this._blurKernelY === value) {
  31822. return;
  31823. }
  31824. this._blurKernelY = value;
  31825. this._preparePostProcesses();
  31826. },
  31827. enumerable: true,
  31828. configurable: true
  31829. });
  31830. MirrorTexture.prototype._preparePostProcesses = function () {
  31831. this.clearPostProcesses(true);
  31832. if (this._blurKernelX && this._blurKernelY) {
  31833. var engine = this.getScene().getEngine();
  31834. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  31835. 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);
  31836. this._blurX.autoClear = false;
  31837. if (this._blurRatio === 1 && this.samples < 2) {
  31838. this._blurX.outputTexture = this._texture;
  31839. }
  31840. else {
  31841. this._blurX.alwaysForcePOT = true;
  31842. }
  31843. 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);
  31844. this._blurY.autoClear = false;
  31845. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  31846. this.addPostProcess(this._blurX);
  31847. this.addPostProcess(this._blurY);
  31848. }
  31849. };
  31850. MirrorTexture.prototype.clone = function () {
  31851. var textureSize = this.getSize();
  31852. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  31853. // Base texture
  31854. newTexture.hasAlpha = this.hasAlpha;
  31855. newTexture.level = this.level;
  31856. // Mirror Texture
  31857. newTexture.mirrorPlane = this.mirrorPlane.clone();
  31858. newTexture.renderList = this.renderList.slice(0);
  31859. return newTexture;
  31860. };
  31861. MirrorTexture.prototype.serialize = function () {
  31862. if (!this.name) {
  31863. return null;
  31864. }
  31865. var serializationObject = _super.prototype.serialize.call(this);
  31866. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  31867. return serializationObject;
  31868. };
  31869. return MirrorTexture;
  31870. }(BABYLON.RenderTargetTexture));
  31871. BABYLON.MirrorTexture = MirrorTexture;
  31872. })(BABYLON || (BABYLON = {}));
  31873. //# sourceMappingURL=babylon.mirrorTexture.js.map
  31874. /// <reference path="babylon.renderTargetTexture.ts" />
  31875. var BABYLON;
  31876. (function (BABYLON) {
  31877. /**
  31878. * Creates a refraction texture used by refraction channel of the standard material.
  31879. * @param name the texture name
  31880. * @param size size of the underlying texture
  31881. * @param scene root scene
  31882. */
  31883. var RefractionTexture = (function (_super) {
  31884. __extends(RefractionTexture, _super);
  31885. function RefractionTexture(name, size, scene, generateMipMaps) {
  31886. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  31887. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  31888. _this.depth = 2.0;
  31889. _this.onBeforeRenderObservable.add(function () {
  31890. scene.clipPlane = _this.refractionPlane;
  31891. });
  31892. _this.onAfterRenderObservable.add(function () {
  31893. delete scene.clipPlane;
  31894. });
  31895. return _this;
  31896. }
  31897. RefractionTexture.prototype.clone = function () {
  31898. var textureSize = this.getSize();
  31899. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  31900. // Base texture
  31901. newTexture.hasAlpha = this.hasAlpha;
  31902. newTexture.level = this.level;
  31903. // Refraction Texture
  31904. newTexture.refractionPlane = this.refractionPlane.clone();
  31905. newTexture.renderList = this.renderList.slice(0);
  31906. newTexture.depth = this.depth;
  31907. return newTexture;
  31908. };
  31909. RefractionTexture.prototype.serialize = function () {
  31910. if (!this.name) {
  31911. return null;
  31912. }
  31913. var serializationObject = _super.prototype.serialize.call(this);
  31914. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  31915. serializationObject.depth = this.depth;
  31916. return serializationObject;
  31917. };
  31918. return RefractionTexture;
  31919. }(BABYLON.RenderTargetTexture));
  31920. BABYLON.RefractionTexture = RefractionTexture;
  31921. })(BABYLON || (BABYLON = {}));
  31922. //# sourceMappingURL=babylon.refractionTexture.js.map
  31923. /// <reference path="babylon.texture.ts" />
  31924. var BABYLON;
  31925. (function (BABYLON) {
  31926. var DynamicTexture = (function (_super) {
  31927. __extends(DynamicTexture, _super);
  31928. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  31929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31930. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31931. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  31932. _this.name = name;
  31933. var engine = _this.getScene().getEngine();
  31934. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31935. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31936. _this._generateMipMaps = generateMipMaps;
  31937. if (options.getContext) {
  31938. _this._canvas = options;
  31939. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31940. }
  31941. else {
  31942. _this._canvas = document.createElement("canvas");
  31943. if (options.width) {
  31944. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31945. }
  31946. else {
  31947. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  31948. }
  31949. }
  31950. var textureSize = _this.getSize();
  31951. _this._canvas.width = textureSize.width;
  31952. _this._canvas.height = textureSize.height;
  31953. _this._context = _this._canvas.getContext("2d");
  31954. return _this;
  31955. }
  31956. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  31957. get: function () {
  31958. return true;
  31959. },
  31960. enumerable: true,
  31961. configurable: true
  31962. });
  31963. DynamicTexture.prototype._recreate = function (textureSize) {
  31964. this._canvas.width = textureSize.width;
  31965. this._canvas.height = textureSize.height;
  31966. this.releaseInternalTexture();
  31967. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  31968. };
  31969. DynamicTexture.prototype.scale = function (ratio) {
  31970. var textureSize = this.getSize();
  31971. textureSize.width *= ratio;
  31972. textureSize.height *= ratio;
  31973. this._recreate(textureSize);
  31974. };
  31975. DynamicTexture.prototype.scaleTo = function (width, height) {
  31976. var textureSize = this.getSize();
  31977. textureSize.width = width;
  31978. textureSize.height = height;
  31979. this._recreate(textureSize);
  31980. };
  31981. DynamicTexture.prototype.getContext = function () {
  31982. return this._context;
  31983. };
  31984. DynamicTexture.prototype.clear = function () {
  31985. var size = this.getSize();
  31986. this._context.fillRect(0, 0, size.width, size.height);
  31987. };
  31988. DynamicTexture.prototype.update = function (invertY) {
  31989. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  31990. };
  31991. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  31992. if (update === void 0) { update = true; }
  31993. var size = this.getSize();
  31994. if (clearColor) {
  31995. this._context.fillStyle = clearColor;
  31996. this._context.fillRect(0, 0, size.width, size.height);
  31997. }
  31998. this._context.font = font;
  31999. if (x === null || x === undefined) {
  32000. var textSize = this._context.measureText(text);
  32001. x = (size.width - textSize.width) / 2;
  32002. }
  32003. if (y === null || y === undefined) {
  32004. var fontSize = parseInt((font.replace(/\D/g, '')));
  32005. ;
  32006. y = (size.height / 2) + (fontSize / 3.65);
  32007. }
  32008. this._context.fillStyle = color;
  32009. this._context.fillText(text, x, y);
  32010. if (update) {
  32011. this.update(invertY);
  32012. }
  32013. };
  32014. DynamicTexture.prototype.clone = function () {
  32015. var textureSize = this.getSize();
  32016. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  32017. // Base texture
  32018. newTexture.hasAlpha = this.hasAlpha;
  32019. newTexture.level = this.level;
  32020. // Dynamic Texture
  32021. newTexture.wrapU = this.wrapU;
  32022. newTexture.wrapV = this.wrapV;
  32023. return newTexture;
  32024. };
  32025. return DynamicTexture;
  32026. }(BABYLON.Texture));
  32027. BABYLON.DynamicTexture = DynamicTexture;
  32028. })(BABYLON || (BABYLON = {}));
  32029. //# sourceMappingURL=babylon.dynamicTexture.js.map
  32030. var BABYLON;
  32031. (function (BABYLON) {
  32032. var VideoTexture = (function (_super) {
  32033. __extends(VideoTexture, _super);
  32034. /**
  32035. * Creates a video texture.
  32036. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  32037. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  32038. * @param {BABYLON.Scene} scene is obviously the current scene.
  32039. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  32040. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  32041. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  32042. */
  32043. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  32044. if (generateMipMaps === void 0) { generateMipMaps = false; }
  32045. if (invertY === void 0) { invertY = false; }
  32046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32047. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32048. _this._autoLaunch = true;
  32049. var urls;
  32050. _this.name = name;
  32051. if (urlsOrVideo instanceof HTMLVideoElement) {
  32052. _this.video = urlsOrVideo;
  32053. }
  32054. else {
  32055. urls = urlsOrVideo;
  32056. _this.video = document.createElement("video");
  32057. _this.video.autoplay = false;
  32058. _this.video.loop = true;
  32059. }
  32060. _this._generateMipMaps = generateMipMaps;
  32061. _this._samplingMode = samplingMode;
  32062. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  32063. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32064. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32065. }
  32066. else {
  32067. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32068. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32069. _this._generateMipMaps = false;
  32070. }
  32071. if (urls) {
  32072. _this.video.addEventListener("canplay", function () {
  32073. _this._createTexture();
  32074. });
  32075. urls.forEach(function (url) {
  32076. var source = document.createElement("source");
  32077. source.src = url;
  32078. _this.video.appendChild(source);
  32079. });
  32080. }
  32081. else {
  32082. _this._createTexture();
  32083. }
  32084. _this._lastUpdate = BABYLON.Tools.Now;
  32085. return _this;
  32086. }
  32087. VideoTexture.prototype.__setTextureReady = function () {
  32088. this._texture.isReady = true;
  32089. };
  32090. VideoTexture.prototype._createTexture = function () {
  32091. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  32092. if (this._autoLaunch) {
  32093. this._autoLaunch = false;
  32094. this.video.play();
  32095. }
  32096. this._setTextureReady = this.__setTextureReady.bind(this);
  32097. this.video.addEventListener("playing", this._setTextureReady);
  32098. };
  32099. VideoTexture.prototype.update = function () {
  32100. var now = BABYLON.Tools.Now;
  32101. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  32102. return false;
  32103. }
  32104. this._lastUpdate = now;
  32105. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  32106. return true;
  32107. };
  32108. VideoTexture.prototype.dispose = function () {
  32109. _super.prototype.dispose.call(this);
  32110. this.video.removeEventListener("playing", this._setTextureReady);
  32111. };
  32112. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  32113. var video = document.createElement("video");
  32114. var constraintsDeviceId;
  32115. if (constraints && constraints.deviceId) {
  32116. constraintsDeviceId = {
  32117. exact: constraints.deviceId
  32118. };
  32119. }
  32120. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  32121. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  32122. if (navigator.getUserMedia) {
  32123. navigator.getUserMedia({
  32124. video: {
  32125. deviceId: constraintsDeviceId,
  32126. width: {
  32127. min: (constraints && constraints.minWidth) || 256,
  32128. max: (constraints && constraints.maxWidth) || 640
  32129. },
  32130. height: {
  32131. min: (constraints && constraints.minHeight) || 256,
  32132. max: (constraints && constraints.maxHeight) || 480
  32133. }
  32134. }
  32135. }, function (stream) {
  32136. if (video.mozSrcObject !== undefined) {
  32137. video.mozSrcObject = stream;
  32138. }
  32139. else {
  32140. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  32141. }
  32142. video.play();
  32143. if (onReady) {
  32144. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  32145. }
  32146. }, function (e) {
  32147. BABYLON.Tools.Error(e.name);
  32148. });
  32149. }
  32150. };
  32151. return VideoTexture;
  32152. }(BABYLON.Texture));
  32153. BABYLON.VideoTexture = VideoTexture;
  32154. })(BABYLON || (BABYLON = {}));
  32155. //# sourceMappingURL=babylon.videoTexture.js.map
  32156. var BABYLON;
  32157. (function (BABYLON) {
  32158. var RawTexture = (function (_super) {
  32159. __extends(RawTexture, _super);
  32160. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32161. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32162. if (invertY === void 0) { invertY = false; }
  32163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32164. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32165. _this.format = format;
  32166. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32167. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32168. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32169. return _this;
  32170. }
  32171. RawTexture.prototype.update = function (data) {
  32172. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32173. };
  32174. // Statics
  32175. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32176. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32177. if (invertY === void 0) { invertY = false; }
  32178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32179. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32180. };
  32181. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32182. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32183. if (invertY === void 0) { invertY = false; }
  32184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32185. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32186. };
  32187. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32189. if (invertY === void 0) { invertY = false; }
  32190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32191. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32192. };
  32193. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32194. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32195. if (invertY === void 0) { invertY = false; }
  32196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32197. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32198. };
  32199. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32200. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32201. if (invertY === void 0) { invertY = false; }
  32202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32203. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32204. };
  32205. return RawTexture;
  32206. }(BABYLON.Texture));
  32207. BABYLON.RawTexture = RawTexture;
  32208. })(BABYLON || (BABYLON = {}));
  32209. //# sourceMappingURL=babylon.rawTexture.js.map
  32210. var BABYLON;
  32211. (function (BABYLON) {
  32212. var Internals;
  32213. (function (Internals) {
  32214. /*
  32215. * Based on jsTGALoader - Javascript loader for TGA file
  32216. * By Vincent Thibault
  32217. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  32218. */
  32219. var TGATools = (function () {
  32220. function TGATools() {
  32221. }
  32222. TGATools.GetTGAHeader = function (data) {
  32223. var offset = 0;
  32224. var header = {
  32225. id_length: data[offset++],
  32226. colormap_type: data[offset++],
  32227. image_type: data[offset++],
  32228. colormap_index: data[offset++] | data[offset++] << 8,
  32229. colormap_length: data[offset++] | data[offset++] << 8,
  32230. colormap_size: data[offset++],
  32231. origin: [
  32232. data[offset++] | data[offset++] << 8,
  32233. data[offset++] | data[offset++] << 8
  32234. ],
  32235. width: data[offset++] | data[offset++] << 8,
  32236. height: data[offset++] | data[offset++] << 8,
  32237. pixel_size: data[offset++],
  32238. flags: data[offset++]
  32239. };
  32240. return header;
  32241. };
  32242. TGATools.UploadContent = function (gl, data) {
  32243. // Not enough data to contain header ?
  32244. if (data.length < 19) {
  32245. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  32246. return;
  32247. }
  32248. // Read Header
  32249. var offset = 18;
  32250. var header = TGATools.GetTGAHeader(data);
  32251. // Assume it's a valid Targa file.
  32252. if (header.id_length + offset > data.length) {
  32253. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  32254. return;
  32255. }
  32256. // Skip not needed data
  32257. offset += header.id_length;
  32258. var use_rle = false;
  32259. var use_pal = false;
  32260. var use_rgb = false;
  32261. var use_grey = false;
  32262. // Get some informations.
  32263. switch (header.image_type) {
  32264. case TGATools._TYPE_RLE_INDEXED:
  32265. use_rle = true;
  32266. case TGATools._TYPE_INDEXED:
  32267. use_pal = true;
  32268. break;
  32269. case TGATools._TYPE_RLE_RGB:
  32270. use_rle = true;
  32271. case TGATools._TYPE_RGB:
  32272. use_rgb = true;
  32273. break;
  32274. case TGATools._TYPE_RLE_GREY:
  32275. use_rle = true;
  32276. case TGATools._TYPE_GREY:
  32277. use_grey = true;
  32278. break;
  32279. }
  32280. var pixel_data;
  32281. var numAlphaBits = header.flags & 0xf;
  32282. var pixel_size = header.pixel_size >> 3;
  32283. var pixel_total = header.width * header.height * pixel_size;
  32284. // Read palettes
  32285. var palettes;
  32286. if (use_pal) {
  32287. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  32288. }
  32289. // Read LRE
  32290. if (use_rle) {
  32291. pixel_data = new Uint8Array(pixel_total);
  32292. var c, count, i;
  32293. var localOffset = 0;
  32294. var pixels = new Uint8Array(pixel_size);
  32295. while (offset < pixel_total && localOffset < pixel_total) {
  32296. c = data[offset++];
  32297. count = (c & 0x7f) + 1;
  32298. // RLE pixels
  32299. if (c & 0x80) {
  32300. // Bind pixel tmp array
  32301. for (i = 0; i < pixel_size; ++i) {
  32302. pixels[i] = data[offset++];
  32303. }
  32304. // Copy pixel array
  32305. for (i = 0; i < count; ++i) {
  32306. pixel_data.set(pixels, localOffset + i * pixel_size);
  32307. }
  32308. localOffset += pixel_size * count;
  32309. }
  32310. else {
  32311. count *= pixel_size;
  32312. for (i = 0; i < count; ++i) {
  32313. pixel_data[localOffset + i] = data[offset++];
  32314. }
  32315. localOffset += count;
  32316. }
  32317. }
  32318. }
  32319. else {
  32320. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  32321. }
  32322. // Load to texture
  32323. var x_start, y_start, x_step, y_step, y_end, x_end;
  32324. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  32325. default:
  32326. case TGATools._ORIGIN_UL:
  32327. x_start = 0;
  32328. x_step = 1;
  32329. x_end = header.width;
  32330. y_start = 0;
  32331. y_step = 1;
  32332. y_end = header.height;
  32333. break;
  32334. case TGATools._ORIGIN_BL:
  32335. x_start = 0;
  32336. x_step = 1;
  32337. x_end = header.width;
  32338. y_start = header.height - 1;
  32339. y_step = -1;
  32340. y_end = -1;
  32341. break;
  32342. case TGATools._ORIGIN_UR:
  32343. x_start = header.width - 1;
  32344. x_step = -1;
  32345. x_end = -1;
  32346. y_start = 0;
  32347. y_step = 1;
  32348. y_end = header.height;
  32349. break;
  32350. case TGATools._ORIGIN_BR:
  32351. x_start = header.width - 1;
  32352. x_step = -1;
  32353. x_end = -1;
  32354. y_start = header.height - 1;
  32355. y_step = -1;
  32356. y_end = -1;
  32357. break;
  32358. }
  32359. // Load the specify method
  32360. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  32361. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  32362. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  32363. };
  32364. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32365. var image = pixel_data, colormap = palettes;
  32366. var width = header.width, height = header.height;
  32367. var color, i = 0, x, y;
  32368. var imageData = new Uint8Array(width * height * 4);
  32369. for (y = y_start; y !== y_end; y += y_step) {
  32370. for (x = x_start; x !== x_end; x += x_step, i++) {
  32371. color = image[i];
  32372. imageData[(x + width * y) * 4 + 3] = 255;
  32373. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  32374. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  32375. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  32376. }
  32377. }
  32378. return imageData;
  32379. };
  32380. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32381. var image = pixel_data;
  32382. var width = header.width, height = header.height;
  32383. var color, i = 0, x, y;
  32384. var imageData = new Uint8Array(width * height * 4);
  32385. for (y = y_start; y !== y_end; y += y_step) {
  32386. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32387. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  32388. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  32389. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  32390. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  32391. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  32392. }
  32393. }
  32394. return imageData;
  32395. };
  32396. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32397. var image = pixel_data;
  32398. var width = header.width, height = header.height;
  32399. var i = 0, x, y;
  32400. var imageData = new Uint8Array(width * height * 4);
  32401. for (y = y_start; y !== y_end; y += y_step) {
  32402. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  32403. imageData[(x + width * y) * 4 + 3] = 255;
  32404. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32405. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32406. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32407. }
  32408. }
  32409. return imageData;
  32410. };
  32411. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32412. var image = pixel_data;
  32413. var width = header.width, height = header.height;
  32414. var i = 0, x, y;
  32415. var imageData = new Uint8Array(width * height * 4);
  32416. for (y = y_start; y !== y_end; y += y_step) {
  32417. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  32418. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32419. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32420. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32421. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  32422. }
  32423. }
  32424. return imageData;
  32425. };
  32426. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32427. var image = pixel_data;
  32428. var width = header.width, height = header.height;
  32429. var color, i = 0, x, y;
  32430. var imageData = new Uint8Array(width * height * 4);
  32431. for (y = y_start; y !== y_end; y += y_step) {
  32432. for (x = x_start; x !== x_end; x += x_step, i++) {
  32433. color = image[i];
  32434. imageData[(x + width * y) * 4 + 0] = color;
  32435. imageData[(x + width * y) * 4 + 1] = color;
  32436. imageData[(x + width * y) * 4 + 2] = color;
  32437. imageData[(x + width * y) * 4 + 3] = 255;
  32438. }
  32439. }
  32440. return imageData;
  32441. };
  32442. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32443. var image = pixel_data;
  32444. var width = header.width, height = header.height;
  32445. var i = 0, x, y;
  32446. var imageData = new Uint8Array(width * height * 4);
  32447. for (y = y_start; y !== y_end; y += y_step) {
  32448. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32449. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  32450. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  32451. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32452. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  32453. }
  32454. }
  32455. return imageData;
  32456. };
  32457. return TGATools;
  32458. }());
  32459. TGATools._TYPE_NO_DATA = 0;
  32460. TGATools._TYPE_INDEXED = 1;
  32461. TGATools._TYPE_RGB = 2;
  32462. TGATools._TYPE_GREY = 3;
  32463. TGATools._TYPE_RLE_INDEXED = 9;
  32464. TGATools._TYPE_RLE_RGB = 10;
  32465. TGATools._TYPE_RLE_GREY = 11;
  32466. TGATools._ORIGIN_MASK = 0x30;
  32467. TGATools._ORIGIN_SHIFT = 0x04;
  32468. TGATools._ORIGIN_BL = 0x00;
  32469. TGATools._ORIGIN_BR = 0x01;
  32470. TGATools._ORIGIN_UL = 0x02;
  32471. TGATools._ORIGIN_UR = 0x03;
  32472. Internals.TGATools = TGATools;
  32473. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32474. })(BABYLON || (BABYLON = {}));
  32475. //# sourceMappingURL=babylon.tga.js.map
  32476. var BABYLON;
  32477. (function (BABYLON) {
  32478. var Internals;
  32479. (function (Internals) {
  32480. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32481. // All values and structures referenced from:
  32482. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32483. var DDS_MAGIC = 0x20534444;
  32484. 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;
  32485. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32486. 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;
  32487. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32488. function FourCCToInt32(value) {
  32489. return value.charCodeAt(0) +
  32490. (value.charCodeAt(1) << 8) +
  32491. (value.charCodeAt(2) << 16) +
  32492. (value.charCodeAt(3) << 24);
  32493. }
  32494. function Int32ToFourCC(value) {
  32495. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32496. }
  32497. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32498. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32499. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32500. var FOURCC_DX10 = FourCCToInt32("DX10");
  32501. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  32502. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  32503. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  32504. var headerLengthInt = 31; // The header length in 32 bit ints
  32505. // Offsets into the header array
  32506. var off_magic = 0;
  32507. var off_size = 1;
  32508. var off_flags = 2;
  32509. var off_height = 3;
  32510. var off_width = 4;
  32511. var off_mipmapCount = 7;
  32512. var off_pfFlags = 20;
  32513. var off_pfFourCC = 21;
  32514. var off_RGBbpp = 22;
  32515. var off_RMask = 23;
  32516. var off_GMask = 24;
  32517. var off_BMask = 25;
  32518. var off_AMask = 26;
  32519. var off_caps1 = 27;
  32520. var off_caps2 = 28;
  32521. var off_caps3 = 29;
  32522. var off_caps4 = 30;
  32523. var off_dxgiFormat = 32;
  32524. ;
  32525. var DDSTools = (function () {
  32526. function DDSTools() {
  32527. }
  32528. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32529. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32530. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  32531. var mipmapCount = 1;
  32532. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32533. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32534. }
  32535. var fourCC = header[off_pfFourCC];
  32536. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  32537. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32538. switch (fourCC) {
  32539. case FOURCC_D3DFMT_R16G16B16A16F:
  32540. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32541. break;
  32542. case FOURCC_D3DFMT_R32G32B32A32F:
  32543. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  32544. break;
  32545. case FOURCC_DX10:
  32546. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  32547. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32548. break;
  32549. }
  32550. }
  32551. return {
  32552. width: header[off_width],
  32553. height: header[off_height],
  32554. mipmapCount: mipmapCount,
  32555. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32556. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32557. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32558. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  32559. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  32560. dxgiFormat: dxgiFormat,
  32561. textureType: textureType
  32562. };
  32563. };
  32564. DDSTools.GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32565. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  32566. };
  32567. DDSTools.GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32568. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  32569. };
  32570. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32571. var byteArray = new Uint8Array(dataLength);
  32572. var srcData = new Uint8Array(arrayBuffer);
  32573. var index = 0;
  32574. for (var y = 0; y < height; y++) {
  32575. for (var x = 0; x < width; x++) {
  32576. var srcPos = dataOffset + (x + y * width) * 4;
  32577. byteArray[index] = srcData[srcPos + 2];
  32578. byteArray[index + 1] = srcData[srcPos + 1];
  32579. byteArray[index + 2] = srcData[srcPos];
  32580. byteArray[index + 3] = srcData[srcPos + 3];
  32581. index += 4;
  32582. }
  32583. }
  32584. return byteArray;
  32585. };
  32586. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32587. var byteArray = new Uint8Array(dataLength);
  32588. var srcData = new Uint8Array(arrayBuffer);
  32589. var index = 0;
  32590. for (var y = 0; y < height; y++) {
  32591. for (var x = 0; x < width; x++) {
  32592. var srcPos = dataOffset + (x + y * width) * 3;
  32593. byteArray[index] = srcData[srcPos + 2];
  32594. byteArray[index + 1] = srcData[srcPos + 1];
  32595. byteArray[index + 2] = srcData[srcPos];
  32596. index += 3;
  32597. }
  32598. }
  32599. return byteArray;
  32600. };
  32601. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32602. var byteArray = new Uint8Array(dataLength);
  32603. var srcData = new Uint8Array(arrayBuffer);
  32604. var index = 0;
  32605. for (var y = 0; y < height; y++) {
  32606. for (var x = 0; x < width; x++) {
  32607. var srcPos = dataOffset + (x + y * width);
  32608. byteArray[index] = srcData[srcPos];
  32609. index++;
  32610. }
  32611. }
  32612. return byteArray;
  32613. };
  32614. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces) {
  32615. var gl = engine._gl;
  32616. var ext = engine.getCaps().s3tc;
  32617. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32618. if (header[off_magic] != DDS_MAGIC) {
  32619. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32620. return;
  32621. }
  32622. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32623. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32624. return;
  32625. }
  32626. if (info.isCompressed && !ext) {
  32627. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  32628. return;
  32629. }
  32630. var bpp = header[off_RGBbpp];
  32631. dataOffset = header[off_size] + 4;
  32632. var computeFormats = false;
  32633. if (info.isFourCC) {
  32634. fourCC = header[off_pfFourCC];
  32635. switch (fourCC) {
  32636. case FOURCC_DXT1:
  32637. blockBytes = 8;
  32638. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32639. break;
  32640. case FOURCC_DXT3:
  32641. blockBytes = 16;
  32642. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32643. break;
  32644. case FOURCC_DXT5:
  32645. blockBytes = 16;
  32646. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32647. break;
  32648. case FOURCC_D3DFMT_R16G16B16A16F:
  32649. computeFormats = true;
  32650. break;
  32651. case FOURCC_D3DFMT_R32G32B32A32F:
  32652. computeFormats = true;
  32653. break;
  32654. case FOURCC_DX10:
  32655. // There is an additionnal header so dataOffset need to be changed
  32656. dataOffset += 5 * 4; // 5 uints
  32657. if (info.dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  32658. computeFormats = true;
  32659. break;
  32660. }
  32661. default:
  32662. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32663. return;
  32664. }
  32665. }
  32666. if (computeFormats) {
  32667. format = engine._getWebGLTextureType(info.textureType);
  32668. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  32669. }
  32670. mipmapCount = 1;
  32671. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  32672. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32673. }
  32674. for (var face = 0; face < faces; face++) {
  32675. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32676. width = header[off_width];
  32677. height = header[off_height];
  32678. for (i = 0; i < mipmapCount; ++i) {
  32679. if (!info.isCompressed && info.isFourCC) {
  32680. dataLength = width * height * 4;
  32681. var floatArray;
  32682. if (bpp === 128) {
  32683. floatArray = DDSTools.GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32684. }
  32685. else {
  32686. floatArray = DDSTools.GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32687. }
  32688. gl.texImage2D(sampler, i, internalFormat, width, height, 0, gl.RGBA, format, floatArray);
  32689. }
  32690. else if (info.isRGB) {
  32691. if (bpp === 24) {
  32692. dataLength = width * height * 3;
  32693. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32694. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  32695. }
  32696. else {
  32697. dataLength = width * height * 4;
  32698. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32699. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  32700. }
  32701. }
  32702. else if (info.isLuminance) {
  32703. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  32704. var unpaddedRowSize = width;
  32705. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  32706. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  32707. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32708. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  32709. }
  32710. else {
  32711. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  32712. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  32713. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  32714. }
  32715. dataOffset += width * height * (bpp / 8);
  32716. width *= 0.5;
  32717. height *= 0.5;
  32718. width = Math.max(1.0, width);
  32719. height = Math.max(1.0, height);
  32720. }
  32721. }
  32722. };
  32723. return DDSTools;
  32724. }());
  32725. Internals.DDSTools = DDSTools;
  32726. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32727. })(BABYLON || (BABYLON = {}));
  32728. //# sourceMappingURL=babylon.dds.js.map
  32729. var BABYLON;
  32730. (function (BABYLON) {
  32731. var Internals;
  32732. (function (Internals) {
  32733. /**
  32734. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  32735. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  32736. */
  32737. var KhronosTextureContainer = (function () {
  32738. /**
  32739. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  32740. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  32741. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  32742. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  32743. */
  32744. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  32745. this.arrayBuffer = arrayBuffer;
  32746. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  32747. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  32748. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  32749. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  32750. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  32751. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  32752. BABYLON.Tools.Error("texture missing KTX identifier");
  32753. return;
  32754. }
  32755. // load the reset of the header in native 32 bit int
  32756. var header = new Int32Array(this.arrayBuffer, 12, 13);
  32757. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  32758. var oppositeEndianess = header[0] === 0x01020304;
  32759. // read all the header elements in order they exist in the file, without modification (sans endainness)
  32760. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  32761. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  32762. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  32763. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  32764. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  32765. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  32766. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  32767. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  32768. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  32769. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  32770. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  32771. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  32772. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  32773. if (this.glType !== 0) {
  32774. BABYLON.Tools.Error("only compressed formats currently supported");
  32775. return;
  32776. }
  32777. else {
  32778. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  32779. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  32780. }
  32781. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  32782. BABYLON.Tools.Error("only 2D textures currently supported");
  32783. return;
  32784. }
  32785. if (this.numberOfArrayElements !== 0) {
  32786. BABYLON.Tools.Error("texture arrays not currently supported");
  32787. return;
  32788. }
  32789. if (this.numberOfFaces !== facesExpected) {
  32790. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  32791. return;
  32792. }
  32793. // we now have a completely validated file, so could use existence of loadType as success
  32794. // would need to make this more elaborate & adjust checks above to support more than one load type
  32795. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  32796. }
  32797. // not as fast hardware based, but will probably never need to use
  32798. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  32799. return ((val & 0xFF) << 24)
  32800. | ((val & 0xFF00) << 8)
  32801. | ((val >> 8) & 0xFF00)
  32802. | ((val >> 24) & 0xFF);
  32803. };
  32804. /**
  32805. * It is assumed that the texture has already been created & is currently bound
  32806. */
  32807. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  32808. switch (this.loadType) {
  32809. case KhronosTextureContainer.COMPRESSED_2D:
  32810. this._upload2DCompressedLevels(gl, loadMipmaps);
  32811. break;
  32812. case KhronosTextureContainer.TEX_2D:
  32813. case KhronosTextureContainer.COMPRESSED_3D:
  32814. case KhronosTextureContainer.TEX_3D:
  32815. }
  32816. };
  32817. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  32818. // initialize width & height for level 1
  32819. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  32820. var width = this.pixelWidth;
  32821. var height = this.pixelHeight;
  32822. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  32823. for (var level = 0; level < mipmapCount; level++) {
  32824. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  32825. for (var face = 0; face < this.numberOfFaces; face++) {
  32826. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32827. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  32828. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  32829. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  32830. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  32831. }
  32832. width = Math.max(1.0, width * 0.5);
  32833. height = Math.max(1.0, height * 0.5);
  32834. }
  32835. };
  32836. return KhronosTextureContainer;
  32837. }());
  32838. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  32839. // load types
  32840. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  32841. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  32842. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  32843. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  32844. Internals.KhronosTextureContainer = KhronosTextureContainer;
  32845. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32846. })(BABYLON || (BABYLON = {}));
  32847. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  32848. var BABYLON;
  32849. (function (BABYLON) {
  32850. var PostProcess = (function () {
  32851. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  32852. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32853. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32854. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  32855. if (blockCompilation === void 0) { blockCompilation = false; }
  32856. this.name = name;
  32857. this.width = -1;
  32858. this.height = -1;
  32859. this.autoClear = true;
  32860. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  32861. /*
  32862. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32863. Can only be used on a single postprocess or on the last one of a chain.
  32864. */
  32865. this.enablePixelPerfectMode = false;
  32866. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  32867. this.alwaysForcePOT = false;
  32868. this.samples = 1;
  32869. this._reusable = false;
  32870. this._textures = new BABYLON.SmartArray(2);
  32871. this._currentRenderTextureInd = 0;
  32872. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32873. this._texelSize = BABYLON.Vector2.Zero();
  32874. // Events
  32875. /**
  32876. * An event triggered when the postprocess is activated.
  32877. * @type {BABYLON.Observable}
  32878. */
  32879. this.onActivateObservable = new BABYLON.Observable();
  32880. /**
  32881. * An event triggered when the postprocess changes its size.
  32882. * @type {BABYLON.Observable}
  32883. */
  32884. this.onSizeChangedObservable = new BABYLON.Observable();
  32885. /**
  32886. * An event triggered when the postprocess applies its effect.
  32887. * @type {BABYLON.Observable}
  32888. */
  32889. this.onApplyObservable = new BABYLON.Observable();
  32890. /**
  32891. * An event triggered before rendering the postprocess
  32892. * @type {BABYLON.Observable}
  32893. */
  32894. this.onBeforeRenderObservable = new BABYLON.Observable();
  32895. /**
  32896. * An event triggered after rendering the postprocess
  32897. * @type {BABYLON.Observable}
  32898. */
  32899. this.onAfterRenderObservable = new BABYLON.Observable();
  32900. if (camera != null) {
  32901. this._camera = camera;
  32902. this._scene = camera.getScene();
  32903. camera.attachPostProcess(this);
  32904. this._engine = this._scene.getEngine();
  32905. }
  32906. else {
  32907. this._engine = engine;
  32908. }
  32909. this._options = options;
  32910. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32911. this._reusable = reusable || false;
  32912. this._textureType = textureType;
  32913. this._samplers = samplers || [];
  32914. this._samplers.push("textureSampler");
  32915. this._fragmentUrl = fragmentUrl;
  32916. this._vertexUrl = vertexUrl;
  32917. this._parameters = parameters || [];
  32918. this._parameters.push("scale");
  32919. this._indexParameters = indexParameters;
  32920. if (!blockCompilation) {
  32921. this.updateEffect(defines);
  32922. }
  32923. }
  32924. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32925. set: function (callback) {
  32926. if (this._onActivateObserver) {
  32927. this.onActivateObservable.remove(this._onActivateObserver);
  32928. }
  32929. this._onActivateObserver = this.onActivateObservable.add(callback);
  32930. },
  32931. enumerable: true,
  32932. configurable: true
  32933. });
  32934. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32935. set: function (callback) {
  32936. if (this._onSizeChangedObserver) {
  32937. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32938. }
  32939. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32940. },
  32941. enumerable: true,
  32942. configurable: true
  32943. });
  32944. Object.defineProperty(PostProcess.prototype, "onApply", {
  32945. set: function (callback) {
  32946. if (this._onApplyObserver) {
  32947. this.onApplyObservable.remove(this._onApplyObserver);
  32948. }
  32949. this._onApplyObserver = this.onApplyObservable.add(callback);
  32950. },
  32951. enumerable: true,
  32952. configurable: true
  32953. });
  32954. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32955. set: function (callback) {
  32956. if (this._onBeforeRenderObserver) {
  32957. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32958. }
  32959. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32960. },
  32961. enumerable: true,
  32962. configurable: true
  32963. });
  32964. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32965. set: function (callback) {
  32966. if (this._onAfterRenderObserver) {
  32967. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32968. }
  32969. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32970. },
  32971. enumerable: true,
  32972. configurable: true
  32973. });
  32974. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  32975. get: function () {
  32976. return this._textures.data[this._currentRenderTextureInd];
  32977. },
  32978. set: function (value) {
  32979. this._forcedOutputTexture = value;
  32980. },
  32981. enumerable: true,
  32982. configurable: true
  32983. });
  32984. PostProcess.prototype.getCamera = function () {
  32985. return this._camera;
  32986. };
  32987. Object.defineProperty(PostProcess.prototype, "texelSize", {
  32988. get: function () {
  32989. if (this._shareOutputWithPostProcess) {
  32990. return this._shareOutputWithPostProcess.texelSize;
  32991. }
  32992. if (this._forcedOutputTexture) {
  32993. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  32994. }
  32995. return this._texelSize;
  32996. },
  32997. enumerable: true,
  32998. configurable: true
  32999. });
  33000. PostProcess.prototype.getEngine = function () {
  33001. return this._engine;
  33002. };
  33003. PostProcess.prototype.getEffect = function () {
  33004. return this._effect;
  33005. };
  33006. PostProcess.prototype.shareOutputWith = function (postProcess) {
  33007. this._disposeTextures();
  33008. this._shareOutputWithPostProcess = postProcess;
  33009. return this;
  33010. };
  33011. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  33012. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  33013. };
  33014. PostProcess.prototype.isReusable = function () {
  33015. return this._reusable;
  33016. };
  33017. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  33018. PostProcess.prototype.markTextureDirty = function () {
  33019. this.width = -1;
  33020. };
  33021. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  33022. var _this = this;
  33023. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  33024. camera = camera || this._camera;
  33025. var scene = camera.getScene();
  33026. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  33027. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  33028. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  33029. var desiredWidth = this._options.width || requiredWidth;
  33030. var desiredHeight = this._options.height || requiredHeight;
  33031. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  33032. if (!this._options.width) {
  33033. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  33034. }
  33035. if (!this._options.height) {
  33036. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  33037. }
  33038. }
  33039. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  33040. if (this._textures.length > 0) {
  33041. for (var i = 0; i < this._textures.length; i++) {
  33042. this._engine._releaseTexture(this._textures.data[i]);
  33043. }
  33044. this._textures.reset();
  33045. }
  33046. this.width = desiredWidth;
  33047. this.height = desiredHeight;
  33048. var textureSize = { width: this.width, height: this.height };
  33049. var textureOptions = {
  33050. generateMipMaps: false,
  33051. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  33052. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  33053. samplingMode: this.renderTargetSamplingMode,
  33054. type: this._textureType
  33055. };
  33056. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  33057. if (this._reusable) {
  33058. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  33059. }
  33060. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  33061. this.onSizeChangedObservable.notifyObservers(this);
  33062. }
  33063. this._textures.forEach(function (texture) {
  33064. if (texture.samples !== _this.samples) {
  33065. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  33066. }
  33067. });
  33068. }
  33069. var target;
  33070. if (this._shareOutputWithPostProcess) {
  33071. target = this._shareOutputWithPostProcess.outputTexture;
  33072. }
  33073. else if (this._forcedOutputTexture) {
  33074. target = this._forcedOutputTexture;
  33075. this.width = this._forcedOutputTexture._width;
  33076. this.height = this._forcedOutputTexture._height;
  33077. }
  33078. else {
  33079. target = this.outputTexture;
  33080. }
  33081. if (this.enablePixelPerfectMode) {
  33082. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  33083. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  33084. }
  33085. else {
  33086. this._scaleRatio.copyFromFloats(1, 1);
  33087. this._engine.bindFramebuffer(target);
  33088. }
  33089. this.onActivateObservable.notifyObservers(camera);
  33090. // Clear
  33091. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  33092. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  33093. }
  33094. if (this._reusable) {
  33095. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  33096. }
  33097. };
  33098. Object.defineProperty(PostProcess.prototype, "isSupported", {
  33099. get: function () {
  33100. return this._effect.isSupported;
  33101. },
  33102. enumerable: true,
  33103. configurable: true
  33104. });
  33105. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  33106. get: function () {
  33107. if (this._shareOutputWithPostProcess) {
  33108. return this._shareOutputWithPostProcess.aspectRatio;
  33109. }
  33110. if (this._forcedOutputTexture) {
  33111. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  33112. }
  33113. return this.width / this.height;
  33114. },
  33115. enumerable: true,
  33116. configurable: true
  33117. });
  33118. PostProcess.prototype.apply = function () {
  33119. // Check
  33120. if (!this._effect || !this._effect.isReady())
  33121. return null;
  33122. // States
  33123. this._engine.enableEffect(this._effect);
  33124. this._engine.setState(false);
  33125. this._engine.setDepthBuffer(false);
  33126. this._engine.setDepthWrite(false);
  33127. // Alpha
  33128. this._engine.setAlphaMode(this.alphaMode);
  33129. if (this.alphaConstants) {
  33130. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  33131. }
  33132. // Texture
  33133. var source;
  33134. if (this._shareOutputWithPostProcess) {
  33135. source = this._shareOutputWithPostProcess.outputTexture;
  33136. }
  33137. else if (this._forcedOutputTexture) {
  33138. source = this._forcedOutputTexture;
  33139. }
  33140. else {
  33141. source = this.outputTexture;
  33142. }
  33143. this._effect._bindTexture("textureSampler", source);
  33144. // Parameters
  33145. this._effect.setVector2("scale", this._scaleRatio);
  33146. this.onApplyObservable.notifyObservers(this._effect);
  33147. return this._effect;
  33148. };
  33149. PostProcess.prototype._disposeTextures = function () {
  33150. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  33151. return;
  33152. }
  33153. if (this._textures.length > 0) {
  33154. for (var i = 0; i < this._textures.length; i++) {
  33155. this._engine._releaseTexture(this._textures.data[i]);
  33156. }
  33157. }
  33158. this._textures.dispose();
  33159. };
  33160. PostProcess.prototype.dispose = function (camera) {
  33161. camera = camera || this._camera;
  33162. this._disposeTextures();
  33163. if (!camera) {
  33164. return;
  33165. }
  33166. camera.detachPostProcess(this);
  33167. var index = camera._postProcesses.indexOf(this);
  33168. if (index === 0 && camera._postProcesses.length > 0) {
  33169. this._camera._postProcesses[0].markTextureDirty();
  33170. }
  33171. this.onActivateObservable.clear();
  33172. this.onAfterRenderObservable.clear();
  33173. this.onApplyObservable.clear();
  33174. this.onBeforeRenderObservable.clear();
  33175. this.onSizeChangedObservable.clear();
  33176. };
  33177. return PostProcess;
  33178. }());
  33179. BABYLON.PostProcess = PostProcess;
  33180. })(BABYLON || (BABYLON = {}));
  33181. //# sourceMappingURL=babylon.postProcess.js.map
  33182. var BABYLON;
  33183. (function (BABYLON) {
  33184. var PassPostProcess = (function (_super) {
  33185. __extends(PassPostProcess, _super);
  33186. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  33187. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33188. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  33189. }
  33190. return PassPostProcess;
  33191. }(BABYLON.PostProcess));
  33192. BABYLON.PassPostProcess = PassPostProcess;
  33193. })(BABYLON || (BABYLON = {}));
  33194. //# sourceMappingURL=babylon.passPostProcess.js.map
  33195. var BABYLON;
  33196. (function (BABYLON) {
  33197. var ShadowGenerator = (function () {
  33198. /**
  33199. * Creates a ShadowGenerator object.
  33200. * A ShadowGenerator is the required tool to use the shadows.
  33201. * Each light casting shadows needs to use its own ShadowGenerator.
  33202. * Required parameters :
  33203. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  33204. * - `light`: the light object generating the shadows.
  33205. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  33206. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  33207. */
  33208. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  33209. // Members
  33210. this._bias = 0.00005;
  33211. this._blurBoxOffset = 1;
  33212. this._blurScale = 2;
  33213. this._blurKernel = 1;
  33214. this._useKernelBlur = false;
  33215. this._filter = ShadowGenerator.FILTER_NONE;
  33216. this._darkness = 0;
  33217. this._transparencyShadow = false;
  33218. this.forceBackFacesOnly = false;
  33219. this._lightDirection = BABYLON.Vector3.Zero();
  33220. this._viewMatrix = BABYLON.Matrix.Zero();
  33221. this._projectionMatrix = BABYLON.Matrix.Zero();
  33222. this._transformMatrix = BABYLON.Matrix.Zero();
  33223. this._worldViewProjection = BABYLON.Matrix.Zero();
  33224. this._currentFaceIndex = 0;
  33225. this._currentFaceIndexCache = 0;
  33226. this._isCube = false;
  33227. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  33228. this._mapSize = mapSize;
  33229. this._light = light;
  33230. this._scene = light.getScene();
  33231. light._shadowGenerator = this;
  33232. // Texture type fallback from float to int if not supported.
  33233. var caps = this._scene.getEngine().getCaps();
  33234. if (!useFullFloatFirst) {
  33235. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33236. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33237. }
  33238. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33239. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33240. }
  33241. else {
  33242. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33243. }
  33244. }
  33245. else {
  33246. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33247. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33248. }
  33249. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33250. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33251. }
  33252. else {
  33253. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33254. }
  33255. }
  33256. this._initializeGenerator();
  33257. }
  33258. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  33259. // Static
  33260. get: function () {
  33261. return ShadowGenerator._FILTER_NONE;
  33262. },
  33263. enumerable: true,
  33264. configurable: true
  33265. });
  33266. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  33267. get: function () {
  33268. return ShadowGenerator._FILTER_POISSONSAMPLING;
  33269. },
  33270. enumerable: true,
  33271. configurable: true
  33272. });
  33273. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  33274. get: function () {
  33275. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  33276. },
  33277. enumerable: true,
  33278. configurable: true
  33279. });
  33280. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  33281. get: function () {
  33282. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  33283. },
  33284. enumerable: true,
  33285. configurable: true
  33286. });
  33287. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  33288. get: function () {
  33289. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33290. },
  33291. enumerable: true,
  33292. configurable: true
  33293. });
  33294. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  33295. get: function () {
  33296. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33297. },
  33298. enumerable: true,
  33299. configurable: true
  33300. });
  33301. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  33302. get: function () {
  33303. return this._bias;
  33304. },
  33305. set: function (bias) {
  33306. this._bias = bias;
  33307. },
  33308. enumerable: true,
  33309. configurable: true
  33310. });
  33311. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  33312. get: function () {
  33313. return this._blurBoxOffset;
  33314. },
  33315. set: function (value) {
  33316. if (this._blurBoxOffset === value) {
  33317. return;
  33318. }
  33319. this._blurBoxOffset = value;
  33320. this._disposeBlurPostProcesses();
  33321. },
  33322. enumerable: true,
  33323. configurable: true
  33324. });
  33325. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  33326. get: function () {
  33327. return this._blurScale;
  33328. },
  33329. set: function (value) {
  33330. if (this._blurScale === value) {
  33331. return;
  33332. }
  33333. this._blurScale = value;
  33334. this._disposeBlurPostProcesses();
  33335. },
  33336. enumerable: true,
  33337. configurable: true
  33338. });
  33339. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  33340. get: function () {
  33341. return this._blurKernel;
  33342. },
  33343. set: function (value) {
  33344. if (this._blurKernel === value) {
  33345. return;
  33346. }
  33347. this._blurKernel = value;
  33348. this._disposeBlurPostProcesses();
  33349. },
  33350. enumerable: true,
  33351. configurable: true
  33352. });
  33353. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  33354. get: function () {
  33355. return this._useKernelBlur;
  33356. },
  33357. set: function (value) {
  33358. if (this._useKernelBlur === value) {
  33359. return;
  33360. }
  33361. this._useKernelBlur = value;
  33362. this._disposeBlurPostProcesses();
  33363. },
  33364. enumerable: true,
  33365. configurable: true
  33366. });
  33367. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  33368. get: function () {
  33369. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  33370. },
  33371. set: function (value) {
  33372. this._depthScale = value;
  33373. },
  33374. enumerable: true,
  33375. configurable: true
  33376. });
  33377. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  33378. get: function () {
  33379. return this._filter;
  33380. },
  33381. set: function (value) {
  33382. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  33383. if (this._light.needCube()) {
  33384. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  33385. this.useExponentialShadowMap = true;
  33386. return;
  33387. }
  33388. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  33389. this.useCloseExponentialShadowMap = true;
  33390. return;
  33391. }
  33392. }
  33393. if (this._filter === value) {
  33394. return;
  33395. }
  33396. this._filter = value;
  33397. this._disposeBlurPostProcesses();
  33398. this._applyFilterValues();
  33399. this._light._markMeshesAsLightDirty();
  33400. },
  33401. enumerable: true,
  33402. configurable: true
  33403. });
  33404. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  33405. get: function () {
  33406. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  33407. },
  33408. set: function (value) {
  33409. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  33410. },
  33411. enumerable: true,
  33412. configurable: true
  33413. });
  33414. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  33415. get: function () {
  33416. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33417. return this.useExponentialShadowMap;
  33418. },
  33419. set: function (value) {
  33420. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33421. this.useExponentialShadowMap = value;
  33422. },
  33423. enumerable: true,
  33424. configurable: true
  33425. });
  33426. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  33427. get: function () {
  33428. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33429. return this.useBlurExponentialShadowMap;
  33430. },
  33431. set: function (value) {
  33432. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33433. this.useBlurExponentialShadowMap = value;
  33434. },
  33435. enumerable: true,
  33436. configurable: true
  33437. });
  33438. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  33439. get: function () {
  33440. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  33441. },
  33442. set: function (value) {
  33443. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33444. },
  33445. enumerable: true,
  33446. configurable: true
  33447. });
  33448. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  33449. get: function () {
  33450. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  33451. },
  33452. set: function (value) {
  33453. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33454. },
  33455. enumerable: true,
  33456. configurable: true
  33457. });
  33458. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  33459. get: function () {
  33460. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33461. },
  33462. set: function (value) {
  33463. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33464. },
  33465. enumerable: true,
  33466. configurable: true
  33467. });
  33468. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  33469. get: function () {
  33470. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33471. },
  33472. set: function (value) {
  33473. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33474. },
  33475. enumerable: true,
  33476. configurable: true
  33477. });
  33478. /**
  33479. * Returns the darkness value (float).
  33480. */
  33481. ShadowGenerator.prototype.getDarkness = function () {
  33482. return this._darkness;
  33483. };
  33484. /**
  33485. * Sets the ShadowGenerator darkness value (float <= 1.0).
  33486. * Returns the ShadowGenerator.
  33487. */
  33488. ShadowGenerator.prototype.setDarkness = function (darkness) {
  33489. if (darkness >= 1.0)
  33490. this._darkness = 1.0;
  33491. else if (darkness <= 0.0)
  33492. this._darkness = 0.0;
  33493. else
  33494. this._darkness = darkness;
  33495. return this;
  33496. };
  33497. /**
  33498. * Sets the ability to have transparent shadow (boolean).
  33499. * Returns the ShadowGenerator.
  33500. */
  33501. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  33502. this._transparencyShadow = hasShadow;
  33503. return this;
  33504. };
  33505. /**
  33506. * Returns a RenderTargetTexture object : the shadow map texture.
  33507. */
  33508. ShadowGenerator.prototype.getShadowMap = function () {
  33509. return this._shadowMap;
  33510. };
  33511. /**
  33512. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  33513. */
  33514. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  33515. if (this._shadowMap2) {
  33516. return this._shadowMap2;
  33517. }
  33518. return this._shadowMap;
  33519. };
  33520. /**
  33521. * Returns the associated light object.
  33522. */
  33523. ShadowGenerator.prototype.getLight = function () {
  33524. return this._light;
  33525. };
  33526. ShadowGenerator.prototype._initializeGenerator = function () {
  33527. this._light._markMeshesAsLightDirty();
  33528. this._initializeShadowMap();
  33529. };
  33530. ShadowGenerator.prototype._initializeShadowMap = function () {
  33531. var _this = this;
  33532. // Render target
  33533. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  33534. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33535. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33536. this._shadowMap.anisotropicFilteringLevel = 1;
  33537. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33538. this._shadowMap.renderParticles = false;
  33539. // Record Face Index before render.
  33540. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  33541. _this._currentFaceIndex = faceIndex;
  33542. });
  33543. // Custom render function.
  33544. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  33545. // Blur if required afer render.
  33546. this._shadowMap.onAfterUnbindObservable.add(function () {
  33547. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  33548. return;
  33549. }
  33550. if (!_this._blurPostProcesses) {
  33551. _this._initializeBlurRTTAndPostProcesses();
  33552. }
  33553. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  33554. });
  33555. // Clear according to the chosen filter.
  33556. this._shadowMap.onClearObservable.add(function (engine) {
  33557. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  33558. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  33559. }
  33560. else {
  33561. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  33562. }
  33563. });
  33564. };
  33565. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  33566. var _this = this;
  33567. var engine = this._scene.getEngine();
  33568. var targetSize = this._mapSize / this.blurScale;
  33569. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  33570. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  33571. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33572. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33573. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33574. }
  33575. if (this.useKernelBlur) {
  33576. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33577. this._kernelBlurXPostprocess.width = targetSize;
  33578. this._kernelBlurXPostprocess.height = targetSize;
  33579. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  33580. effect.setTexture("textureSampler", _this._shadowMap);
  33581. });
  33582. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33583. this._kernelBlurXPostprocess.autoClear = false;
  33584. this._kernelBlurYPostprocess.autoClear = false;
  33585. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33586. this._kernelBlurXPostprocess.packedFloat = true;
  33587. this._kernelBlurYPostprocess.packedFloat = true;
  33588. }
  33589. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  33590. }
  33591. else {
  33592. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  33593. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  33594. effect.setFloat2("screenSize", targetSize, targetSize);
  33595. effect.setTexture("textureSampler", _this._shadowMap);
  33596. });
  33597. this._boxBlurPostprocess.autoClear = false;
  33598. this._blurPostProcesses = [this._boxBlurPostprocess];
  33599. }
  33600. };
  33601. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33602. var index;
  33603. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33604. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  33605. }
  33606. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33607. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  33608. }
  33609. if (this._transparencyShadow) {
  33610. for (index = 0; index < transparentSubMeshes.length; index++) {
  33611. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  33612. }
  33613. }
  33614. };
  33615. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  33616. var _this = this;
  33617. var mesh = subMesh.getRenderingMesh();
  33618. var scene = this._scene;
  33619. var engine = scene.getEngine();
  33620. // Culling
  33621. engine.setState(subMesh.getMaterial().backFaceCulling);
  33622. // Managing instances
  33623. var batch = mesh._getInstancesRenderList(subMesh._id);
  33624. if (batch.mustReturn) {
  33625. return;
  33626. }
  33627. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33628. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  33629. engine.enableEffect(this._effect);
  33630. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33631. var material = subMesh.getMaterial();
  33632. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  33633. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  33634. this._effect.setVector3("lightPosition", this.getLight().position);
  33635. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  33636. // Alpha test
  33637. if (material && material.needAlphaTesting()) {
  33638. var alphaTexture = material.getAlphaTestTexture();
  33639. if (alphaTexture) {
  33640. this._effect.setTexture("diffuseSampler", alphaTexture);
  33641. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  33642. }
  33643. }
  33644. // Bones
  33645. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33646. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33647. }
  33648. if (this.forceBackFacesOnly) {
  33649. engine.setState(true, 0, false, true);
  33650. }
  33651. // Draw
  33652. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33653. if (this.forceBackFacesOnly) {
  33654. engine.setState(true, 0, false, false);
  33655. }
  33656. }
  33657. else {
  33658. // Need to reset refresh rate of the shadowMap
  33659. this._shadowMap.resetRefreshCounter();
  33660. }
  33661. };
  33662. ShadowGenerator.prototype._applyFilterValues = function () {
  33663. if (this.filter === ShadowGenerator.FILTER_NONE) {
  33664. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  33665. }
  33666. else {
  33667. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33668. }
  33669. };
  33670. /**
  33671. * Boolean : true when the ShadowGenerator is finally computed.
  33672. */
  33673. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  33674. var defines = [];
  33675. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33676. defines.push("#define FLOAT");
  33677. }
  33678. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33679. defines.push("#define ESM");
  33680. }
  33681. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33682. var mesh = subMesh.getMesh();
  33683. var material = subMesh.getMaterial();
  33684. // Alpha test
  33685. if (material && material.needAlphaTesting()) {
  33686. var alphaTexture = material.getAlphaTestTexture();
  33687. if (alphaTexture) {
  33688. defines.push("#define ALPHATEST");
  33689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33690. attribs.push(BABYLON.VertexBuffer.UVKind);
  33691. defines.push("#define UV1");
  33692. }
  33693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33694. if (alphaTexture.coordinatesIndex === 1) {
  33695. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33696. defines.push("#define UV2");
  33697. }
  33698. }
  33699. }
  33700. }
  33701. // Bones
  33702. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33705. if (mesh.numBoneInfluencers > 4) {
  33706. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33707. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33708. }
  33709. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33710. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33711. }
  33712. else {
  33713. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33714. }
  33715. // Instances
  33716. if (useInstances) {
  33717. defines.push("#define INSTANCES");
  33718. attribs.push("world0");
  33719. attribs.push("world1");
  33720. attribs.push("world2");
  33721. attribs.push("world3");
  33722. }
  33723. // Get correct effect
  33724. var join = defines.join("\n");
  33725. if (this._cachedDefines !== join) {
  33726. this._cachedDefines = join;
  33727. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  33728. }
  33729. return this._effect.isReady();
  33730. };
  33731. /**
  33732. * This creates the defines related to the standard BJS materials.
  33733. */
  33734. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  33735. var scene = this._scene;
  33736. var light = this._light;
  33737. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33738. return;
  33739. }
  33740. defines["SHADOW" + lightIndex] = true;
  33741. if (this.usePoissonSampling) {
  33742. defines["SHADOWPCF" + lightIndex] = true;
  33743. }
  33744. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33745. defines["SHADOWESM" + lightIndex] = true;
  33746. }
  33747. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  33748. defines["SHADOWCLOSEESM" + lightIndex] = true;
  33749. }
  33750. if (light.needCube()) {
  33751. defines["SHADOWCUBE" + lightIndex] = true;
  33752. }
  33753. };
  33754. /**
  33755. * This binds shadow lights related to the standard BJS materials.
  33756. * It implies the unifroms available on the materials are the standard BJS ones.
  33757. */
  33758. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  33759. var light = this._light;
  33760. var scene = this._scene;
  33761. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33762. return;
  33763. }
  33764. if (!light.needCube()) {
  33765. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  33766. }
  33767. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  33768. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  33769. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  33770. };
  33771. // Methods
  33772. /**
  33773. * Returns a Matrix object : the updated transformation matrix.
  33774. */
  33775. ShadowGenerator.prototype.getTransformMatrix = function () {
  33776. var scene = this._scene;
  33777. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  33778. return this._transformMatrix;
  33779. }
  33780. this._currentRenderID = scene.getRenderId();
  33781. this._currentFaceIndexCache = this._currentFaceIndex;
  33782. var lightPosition = this._light.position;
  33783. if (this._light.computeTransformedInformation()) {
  33784. lightPosition = this._light.transformedPosition;
  33785. }
  33786. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  33787. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  33788. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  33789. }
  33790. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  33791. this._cachedPosition = lightPosition.clone();
  33792. this._cachedDirection = this._lightDirection.clone();
  33793. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  33794. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  33795. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  33796. }
  33797. return this._transformMatrix;
  33798. };
  33799. ShadowGenerator.prototype.recreateShadowMap = function () {
  33800. // Track render list.
  33801. var renderList = this._shadowMap.renderList;
  33802. // Clean up existing data.
  33803. this._disposeRTTandPostProcesses();
  33804. // Reinitializes.
  33805. this._initializeGenerator();
  33806. // Reaffect the filter to ensure a correct fallback if necessary.
  33807. this.filter = this.filter;
  33808. // Reaffect the filter.
  33809. this._applyFilterValues();
  33810. // Reaffect Render List.
  33811. this._shadowMap.renderList = renderList;
  33812. };
  33813. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  33814. if (this._shadowMap2) {
  33815. this._shadowMap2.dispose();
  33816. this._shadowMap2 = null;
  33817. }
  33818. if (this._downSamplePostprocess) {
  33819. this._downSamplePostprocess.dispose();
  33820. this._downSamplePostprocess = null;
  33821. }
  33822. if (this._boxBlurPostprocess) {
  33823. this._boxBlurPostprocess.dispose();
  33824. this._boxBlurPostprocess = null;
  33825. }
  33826. if (this._kernelBlurXPostprocess) {
  33827. this._kernelBlurXPostprocess.dispose();
  33828. this._kernelBlurXPostprocess = null;
  33829. }
  33830. if (this._kernelBlurYPostprocess) {
  33831. this._kernelBlurYPostprocess.dispose();
  33832. this._kernelBlurYPostprocess = null;
  33833. }
  33834. this._blurPostProcesses = null;
  33835. };
  33836. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  33837. if (this._shadowMap) {
  33838. this._shadowMap.dispose();
  33839. this._shadowMap = null;
  33840. }
  33841. this._disposeBlurPostProcesses();
  33842. };
  33843. /**
  33844. * Disposes the ShadowGenerator.
  33845. * Returns nothing.
  33846. */
  33847. ShadowGenerator.prototype.dispose = function () {
  33848. this._disposeRTTandPostProcesses();
  33849. this._light._shadowGenerator = null;
  33850. this._light._markMeshesAsLightDirty();
  33851. };
  33852. /**
  33853. * Serializes the ShadowGenerator and returns a serializationObject.
  33854. */
  33855. ShadowGenerator.prototype.serialize = function () {
  33856. var serializationObject = {};
  33857. var shadowMap = this.getShadowMap();
  33858. serializationObject.lightId = this._light.id;
  33859. serializationObject.mapSize = shadowMap.getRenderSize();
  33860. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  33861. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  33862. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33863. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33864. serializationObject.usePoissonSampling = this.usePoissonSampling;
  33865. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  33866. serializationObject.depthScale = this.depthScale;
  33867. serializationObject.darkness = this.getDarkness();
  33868. serializationObject.blurBoxOffset = this.blurBoxOffset;
  33869. serializationObject.blurKernel = this.blurKernel;
  33870. serializationObject.blurScale = this.blurScale;
  33871. serializationObject.useKernelBlur = this.useKernelBlur;
  33872. serializationObject.transparencyShadow = this._transparencyShadow;
  33873. serializationObject.renderList = [];
  33874. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  33875. var mesh = shadowMap.renderList[meshIndex];
  33876. serializationObject.renderList.push(mesh.id);
  33877. }
  33878. return serializationObject;
  33879. };
  33880. /**
  33881. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  33882. */
  33883. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  33884. //casting to point light, as light is missing the position attr and typescript complains.
  33885. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  33886. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  33887. var shadowMap = shadowGenerator.getShadowMap();
  33888. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  33889. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  33890. meshes.forEach(function (mesh) {
  33891. shadowMap.renderList.push(mesh);
  33892. });
  33893. }
  33894. if (parsedShadowGenerator.usePoissonSampling) {
  33895. shadowGenerator.usePoissonSampling = true;
  33896. }
  33897. else if (parsedShadowGenerator.useExponentialShadowMap) {
  33898. shadowGenerator.useExponentialShadowMap = true;
  33899. }
  33900. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33901. shadowGenerator.useBlurExponentialShadowMap = true;
  33902. }
  33903. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  33904. shadowGenerator.useCloseExponentialShadowMap = true;
  33905. }
  33906. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33907. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  33908. }
  33909. else if (parsedShadowGenerator.useVarianceShadowMap) {
  33910. shadowGenerator.useExponentialShadowMap = true;
  33911. }
  33912. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  33913. shadowGenerator.useBlurExponentialShadowMap = true;
  33914. }
  33915. if (parsedShadowGenerator.depthScale) {
  33916. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  33917. }
  33918. if (parsedShadowGenerator.blurScale) {
  33919. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  33920. }
  33921. if (parsedShadowGenerator.blurBoxOffset) {
  33922. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  33923. }
  33924. if (parsedShadowGenerator.useKernelBlur) {
  33925. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  33926. }
  33927. if (parsedShadowGenerator.blurKernel) {
  33928. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  33929. }
  33930. if (parsedShadowGenerator.bias !== undefined) {
  33931. shadowGenerator.bias = parsedShadowGenerator.bias;
  33932. }
  33933. if (parsedShadowGenerator.darkness) {
  33934. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  33935. }
  33936. if (parsedShadowGenerator.transparencyShadow) {
  33937. shadowGenerator.setTransparencyShadow(true);
  33938. }
  33939. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  33940. return shadowGenerator;
  33941. };
  33942. return ShadowGenerator;
  33943. }());
  33944. ShadowGenerator._FILTER_NONE = 0;
  33945. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  33946. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  33947. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  33948. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  33949. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  33950. BABYLON.ShadowGenerator = ShadowGenerator;
  33951. })(BABYLON || (BABYLON = {}));
  33952. //# sourceMappingURL=babylon.shadowGenerator.js.map
  33953. var BABYLON;
  33954. (function (BABYLON) {
  33955. var ShadowLight = (function (_super) {
  33956. __extends(ShadowLight, _super);
  33957. function ShadowLight() {
  33958. var _this = _super !== null && _super.apply(this, arguments) || this;
  33959. _this._needProjectionMatrixCompute = true;
  33960. return _this;
  33961. }
  33962. Object.defineProperty(ShadowLight.prototype, "direction", {
  33963. get: function () {
  33964. return this._direction;
  33965. },
  33966. set: function (value) {
  33967. this._direction = value;
  33968. },
  33969. enumerable: true,
  33970. configurable: true
  33971. });
  33972. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33973. get: function () {
  33974. return this._shadowMinZ;
  33975. },
  33976. set: function (value) {
  33977. this._shadowMinZ = value;
  33978. this.forceProjectionMatrixCompute();
  33979. },
  33980. enumerable: true,
  33981. configurable: true
  33982. });
  33983. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33984. get: function () {
  33985. return this._shadowMaxZ;
  33986. },
  33987. set: function (value) {
  33988. this._shadowMaxZ = value;
  33989. this.forceProjectionMatrixCompute();
  33990. },
  33991. enumerable: true,
  33992. configurable: true
  33993. });
  33994. /**
  33995. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33996. */
  33997. ShadowLight.prototype.computeTransformedInformation = function () {
  33998. if (this.parent && this.parent.getWorldMatrix) {
  33999. if (!this.transformedPosition) {
  34000. this.transformedPosition = BABYLON.Vector3.Zero();
  34001. }
  34002. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  34003. // In case the direction is present.
  34004. if (this.direction) {
  34005. if (!this.transformedDirection) {
  34006. this.transformedDirection = BABYLON.Vector3.Zero();
  34007. }
  34008. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  34009. }
  34010. return true;
  34011. }
  34012. return false;
  34013. };
  34014. /**
  34015. * Return the depth scale used for the shadow map.
  34016. */
  34017. ShadowLight.prototype.getDepthScale = function () {
  34018. return 50.0;
  34019. };
  34020. /**
  34021. * Returns the light direction (Vector3) for any passed face index.
  34022. */
  34023. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  34024. return this.transformedDirection ? this.transformedDirection : this.direction;
  34025. };
  34026. /**
  34027. * Returns the DirectionalLight absolute position in the World.
  34028. */
  34029. ShadowLight.prototype.getAbsolutePosition = function () {
  34030. return this.transformedPosition ? this.transformedPosition : this.position;
  34031. };
  34032. /**
  34033. * Sets the DirectionalLight direction toward the passed target (Vector3).
  34034. * Returns the updated DirectionalLight direction (Vector3).
  34035. */
  34036. ShadowLight.prototype.setDirectionToTarget = function (target) {
  34037. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  34038. return this.direction;
  34039. };
  34040. /**
  34041. * Returns the light rotation (Vector3).
  34042. */
  34043. ShadowLight.prototype.getRotation = function () {
  34044. this.direction.normalize();
  34045. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  34046. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  34047. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  34048. };
  34049. /**
  34050. * Boolean : false by default.
  34051. */
  34052. ShadowLight.prototype.needCube = function () {
  34053. return false;
  34054. };
  34055. /**
  34056. * Specifies wether or not the projection matrix should be recomputed this frame.
  34057. */
  34058. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  34059. return this._needProjectionMatrixCompute;
  34060. };
  34061. /**
  34062. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  34063. */
  34064. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  34065. this._needProjectionMatrixCompute = true;
  34066. };
  34067. /**
  34068. * Get the world matrix of the sahdow lights.
  34069. */
  34070. ShadowLight.prototype._getWorldMatrix = function () {
  34071. if (!this._worldMatrix) {
  34072. this._worldMatrix = BABYLON.Matrix.Identity();
  34073. }
  34074. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  34075. return this._worldMatrix;
  34076. };
  34077. /**
  34078. * Gets the minZ used for shadow according to both the scene and the light.
  34079. * @param activeCamera
  34080. */
  34081. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  34082. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  34083. };
  34084. /**
  34085. * Gets the maxZ used for shadow according to both the scene and the light.
  34086. * @param activeCamera
  34087. */
  34088. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  34089. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  34090. };
  34091. /**
  34092. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  34093. * Returns the light.
  34094. */
  34095. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34096. if (this.customProjectionMatrixBuilder) {
  34097. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  34098. }
  34099. else {
  34100. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34101. }
  34102. return this;
  34103. };
  34104. return ShadowLight;
  34105. }(BABYLON.Light));
  34106. __decorate([
  34107. BABYLON.serializeAsVector3()
  34108. ], ShadowLight.prototype, "position", void 0);
  34109. __decorate([
  34110. BABYLON.serializeAsVector3()
  34111. ], ShadowLight.prototype, "direction", null);
  34112. __decorate([
  34113. BABYLON.serialize()
  34114. ], ShadowLight.prototype, "shadowMinZ", null);
  34115. __decorate([
  34116. BABYLON.serialize()
  34117. ], ShadowLight.prototype, "shadowMaxZ", null);
  34118. BABYLON.ShadowLight = ShadowLight;
  34119. })(BABYLON || (BABYLON = {}));
  34120. //# sourceMappingURL=babylon.shadowLight.js.map
  34121. var BABYLON;
  34122. (function (BABYLON) {
  34123. var PointLight = (function (_super) {
  34124. __extends(PointLight, _super);
  34125. /**
  34126. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  34127. * A PointLight emits the light in every direction.
  34128. * It can cast shadows.
  34129. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  34130. * ```javascript
  34131. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  34132. * ```
  34133. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34134. */
  34135. function PointLight(name, position, scene) {
  34136. var _this = _super.call(this, name, scene) || this;
  34137. _this._shadowAngle = Math.PI / 2;
  34138. _this.position = position;
  34139. return _this;
  34140. }
  34141. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  34142. /**
  34143. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34144. * This specifies what angle the shadow will use to be created.
  34145. *
  34146. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34147. */
  34148. get: function () {
  34149. return this._shadowAngle;
  34150. },
  34151. /**
  34152. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34153. * This specifies what angle the shadow will use to be created.
  34154. *
  34155. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34156. */
  34157. set: function (value) {
  34158. this._shadowAngle = value;
  34159. this.forceProjectionMatrixCompute();
  34160. },
  34161. enumerable: true,
  34162. configurable: true
  34163. });
  34164. Object.defineProperty(PointLight.prototype, "direction", {
  34165. get: function () {
  34166. return this._direction;
  34167. },
  34168. /**
  34169. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34170. */
  34171. set: function (value) {
  34172. var previousNeedCube = this.needCube();
  34173. this._direction = value;
  34174. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  34175. this._shadowGenerator.recreateShadowMap();
  34176. }
  34177. },
  34178. enumerable: true,
  34179. configurable: true
  34180. });
  34181. /**
  34182. * Returns the string "PointLight"
  34183. */
  34184. PointLight.prototype.getClassName = function () {
  34185. return "PointLight";
  34186. };
  34187. /**
  34188. * Returns the integer 0.
  34189. */
  34190. PointLight.prototype.getTypeID = function () {
  34191. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  34192. };
  34193. /**
  34194. * Specifies wether or not the shadowmap should be a cube texture.
  34195. */
  34196. PointLight.prototype.needCube = function () {
  34197. return !this.direction;
  34198. };
  34199. /**
  34200. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  34201. */
  34202. PointLight.prototype.getShadowDirection = function (faceIndex) {
  34203. if (this.direction) {
  34204. return _super.prototype.getShadowDirection.call(this, faceIndex);
  34205. }
  34206. else {
  34207. switch (faceIndex) {
  34208. case 0:
  34209. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  34210. case 1:
  34211. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  34212. case 2:
  34213. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  34214. case 3:
  34215. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  34216. case 4:
  34217. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  34218. case 5:
  34219. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  34220. }
  34221. }
  34222. return BABYLON.Vector3.Zero();
  34223. };
  34224. /**
  34225. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  34226. * - fov = PI / 2
  34227. * - aspect ratio : 1.0
  34228. * - z-near and far equal to the active camera minZ and maxZ.
  34229. * Returns the PointLight.
  34230. */
  34231. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34232. var activeCamera = this.getScene().activeCamera;
  34233. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34234. };
  34235. PointLight.prototype._buildUniformLayout = function () {
  34236. this._uniformBuffer.addUniform("vLightData", 4);
  34237. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34238. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34239. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34240. this._uniformBuffer.addUniform("depthValues", 2);
  34241. this._uniformBuffer.create();
  34242. };
  34243. /**
  34244. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34245. * Returns the PointLight.
  34246. */
  34247. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34248. if (this.computeTransformedInformation()) {
  34249. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34250. return this;
  34251. }
  34252. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34253. return this;
  34254. };
  34255. return PointLight;
  34256. }(BABYLON.ShadowLight));
  34257. __decorate([
  34258. BABYLON.serialize()
  34259. ], PointLight.prototype, "shadowAngle", null);
  34260. BABYLON.PointLight = PointLight;
  34261. })(BABYLON || (BABYLON = {}));
  34262. //# sourceMappingURL=babylon.pointLight.js.map
  34263. /// <reference path="babylon.light.ts" />
  34264. var BABYLON;
  34265. (function (BABYLON) {
  34266. var DirectionalLight = (function (_super) {
  34267. __extends(DirectionalLight, _super);
  34268. /**
  34269. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34270. * The directional light is emitted from everywhere in the given direction.
  34271. * It can cast shawdows.
  34272. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34273. */
  34274. function DirectionalLight(name, direction, scene) {
  34275. var _this = _super.call(this, name, scene) || this;
  34276. _this._shadowFrustumSize = 0;
  34277. _this._shadowOrthoScale = 0.5;
  34278. _this.autoUpdateExtends = true;
  34279. // Cache
  34280. _this._orthoLeft = Number.MAX_VALUE;
  34281. _this._orthoRight = Number.MIN_VALUE;
  34282. _this._orthoTop = Number.MIN_VALUE;
  34283. _this._orthoBottom = Number.MAX_VALUE;
  34284. _this.position = direction.scale(-1.0);
  34285. _this.direction = direction;
  34286. return _this;
  34287. }
  34288. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34289. /**
  34290. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34291. */
  34292. get: function () {
  34293. return this._shadowFrustumSize;
  34294. },
  34295. /**
  34296. * Specifies a fix frustum size for the shadow generation.
  34297. */
  34298. set: function (value) {
  34299. this._shadowFrustumSize = value;
  34300. this.forceProjectionMatrixCompute();
  34301. },
  34302. enumerable: true,
  34303. configurable: true
  34304. });
  34305. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34306. get: function () {
  34307. return this._shadowOrthoScale;
  34308. },
  34309. set: function (value) {
  34310. this._shadowOrthoScale = value;
  34311. this.forceProjectionMatrixCompute();
  34312. },
  34313. enumerable: true,
  34314. configurable: true
  34315. });
  34316. /**
  34317. * Returns the string "DirectionalLight".
  34318. */
  34319. DirectionalLight.prototype.getClassName = function () {
  34320. return "DirectionalLight";
  34321. };
  34322. /**
  34323. * Returns the integer 1.
  34324. */
  34325. DirectionalLight.prototype.getTypeID = function () {
  34326. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34327. };
  34328. /**
  34329. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34330. * Returns the DirectionalLight Shadow projection matrix.
  34331. */
  34332. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34333. if (this.shadowFrustumSize > 0) {
  34334. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34335. }
  34336. else {
  34337. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34338. }
  34339. };
  34340. /**
  34341. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34342. * Returns the DirectionalLight Shadow projection matrix.
  34343. */
  34344. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34345. var activeCamera = this.getScene().activeCamera;
  34346. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34347. };
  34348. /**
  34349. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34350. * Returns the DirectionalLight Shadow projection matrix.
  34351. */
  34352. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34353. var activeCamera = this.getScene().activeCamera;
  34354. // Check extends
  34355. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34356. var tempVector3 = BABYLON.Vector3.Zero();
  34357. this._orthoLeft = Number.MAX_VALUE;
  34358. this._orthoRight = Number.MIN_VALUE;
  34359. this._orthoTop = Number.MIN_VALUE;
  34360. this._orthoBottom = Number.MAX_VALUE;
  34361. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34362. var mesh = renderList[meshIndex];
  34363. if (!mesh) {
  34364. continue;
  34365. }
  34366. var boundingInfo = mesh.getBoundingInfo();
  34367. if (!boundingInfo) {
  34368. continue;
  34369. }
  34370. var boundingBox = boundingInfo.boundingBox;
  34371. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34372. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34373. if (tempVector3.x < this._orthoLeft)
  34374. this._orthoLeft = tempVector3.x;
  34375. if (tempVector3.y < this._orthoBottom)
  34376. this._orthoBottom = tempVector3.y;
  34377. if (tempVector3.x > this._orthoRight)
  34378. this._orthoRight = tempVector3.x;
  34379. if (tempVector3.y > this._orthoTop)
  34380. this._orthoTop = tempVector3.y;
  34381. }
  34382. }
  34383. }
  34384. var xOffset = this._orthoRight - this._orthoLeft;
  34385. var yOffset = this._orthoTop - this._orthoBottom;
  34386. 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);
  34387. };
  34388. DirectionalLight.prototype._buildUniformLayout = function () {
  34389. this._uniformBuffer.addUniform("vLightData", 4);
  34390. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34391. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34392. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34393. this._uniformBuffer.addUniform("depthValues", 2);
  34394. this._uniformBuffer.create();
  34395. };
  34396. /**
  34397. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34398. * Returns the DirectionalLight.
  34399. */
  34400. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34401. if (this.computeTransformedInformation()) {
  34402. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34403. return this;
  34404. }
  34405. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34406. return this;
  34407. };
  34408. /**
  34409. * Gets the minZ used for shadow according to both the scene and the light.
  34410. *
  34411. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34412. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34413. * @param activeCamera
  34414. */
  34415. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34416. return 1;
  34417. };
  34418. /**
  34419. * Gets the maxZ used for shadow according to both the scene and the light.
  34420. *
  34421. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34422. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34423. * @param activeCamera
  34424. */
  34425. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34426. return 1;
  34427. };
  34428. return DirectionalLight;
  34429. }(BABYLON.ShadowLight));
  34430. __decorate([
  34431. BABYLON.serialize()
  34432. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34433. __decorate([
  34434. BABYLON.serialize()
  34435. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34436. __decorate([
  34437. BABYLON.serialize()
  34438. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34439. BABYLON.DirectionalLight = DirectionalLight;
  34440. })(BABYLON || (BABYLON = {}));
  34441. //# sourceMappingURL=babylon.directionalLight.js.map
  34442. var BABYLON;
  34443. (function (BABYLON) {
  34444. var SpotLight = (function (_super) {
  34445. __extends(SpotLight, _super);
  34446. /**
  34447. * Creates a SpotLight object in the scene with the passed parameters :
  34448. * - `position` (Vector3) is the initial SpotLight position,
  34449. * - `direction` (Vector3) is the initial SpotLight direction,
  34450. * - `angle` (float, in radians) is the spot light cone angle,
  34451. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34452. * A spot light is a simply light oriented cone.
  34453. * It can cast shadows.
  34454. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34455. */
  34456. function SpotLight(name, position, direction, angle, exponent, scene) {
  34457. var _this = _super.call(this, name, scene) || this;
  34458. _this.position = position;
  34459. _this.direction = direction;
  34460. _this.angle = angle;
  34461. _this.exponent = exponent;
  34462. return _this;
  34463. }
  34464. Object.defineProperty(SpotLight.prototype, "angle", {
  34465. get: function () {
  34466. return this._angle;
  34467. },
  34468. set: function (value) {
  34469. this._angle = value;
  34470. this.forceProjectionMatrixCompute();
  34471. },
  34472. enumerable: true,
  34473. configurable: true
  34474. });
  34475. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34476. get: function () {
  34477. return this._shadowAngleScale;
  34478. },
  34479. /**
  34480. * Allows scaling the angle of the light for shadow generation only.
  34481. */
  34482. set: function (value) {
  34483. this._shadowAngleScale = value;
  34484. this.forceProjectionMatrixCompute();
  34485. },
  34486. enumerable: true,
  34487. configurable: true
  34488. });
  34489. /**
  34490. * Returns the string "SpotLight".
  34491. */
  34492. SpotLight.prototype.getClassName = function () {
  34493. return "SpotLight";
  34494. };
  34495. /**
  34496. * Returns the integer 2.
  34497. */
  34498. SpotLight.prototype.getTypeID = function () {
  34499. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34500. };
  34501. /**
  34502. * 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.
  34503. * Returns the SpotLight.
  34504. */
  34505. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34506. var activeCamera = this.getScene().activeCamera;
  34507. this._shadowAngleScale = this._shadowAngleScale || 1;
  34508. var angle = this._shadowAngleScale * this._angle;
  34509. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34510. };
  34511. SpotLight.prototype._buildUniformLayout = function () {
  34512. this._uniformBuffer.addUniform("vLightData", 4);
  34513. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34514. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34515. this._uniformBuffer.addUniform("vLightDirection", 3);
  34516. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34517. this._uniformBuffer.addUniform("depthValues", 2);
  34518. this._uniformBuffer.create();
  34519. };
  34520. /**
  34521. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34522. * Return the SpotLight.
  34523. */
  34524. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34525. var normalizeDirection;
  34526. if (this.computeTransformedInformation()) {
  34527. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34528. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34529. }
  34530. else {
  34531. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34532. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34533. }
  34534. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34535. return this;
  34536. };
  34537. return SpotLight;
  34538. }(BABYLON.ShadowLight));
  34539. __decorate([
  34540. BABYLON.serialize()
  34541. ], SpotLight.prototype, "angle", null);
  34542. __decorate([
  34543. BABYLON.serialize()
  34544. /**
  34545. * Allows scaling the angle of the light for shadow generation only.
  34546. */
  34547. ], SpotLight.prototype, "shadowAngleScale", null);
  34548. __decorate([
  34549. BABYLON.serialize()
  34550. ], SpotLight.prototype, "exponent", void 0);
  34551. BABYLON.SpotLight = SpotLight;
  34552. })(BABYLON || (BABYLON = {}));
  34553. //# sourceMappingURL=babylon.spotLight.js.map
  34554. var BABYLON;
  34555. (function (BABYLON) {
  34556. var MultiMaterial = (function (_super) {
  34557. __extends(MultiMaterial, _super);
  34558. function MultiMaterial(name, scene) {
  34559. var _this = _super.call(this, name, scene, true) || this;
  34560. scene.multiMaterials.push(_this);
  34561. _this.subMaterials = new Array();
  34562. return _this;
  34563. }
  34564. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  34565. get: function () {
  34566. return this._subMaterials;
  34567. },
  34568. set: function (value) {
  34569. this._subMaterials = value;
  34570. this._hookArray(value);
  34571. },
  34572. enumerable: true,
  34573. configurable: true
  34574. });
  34575. MultiMaterial.prototype._hookArray = function (array) {
  34576. var _this = this;
  34577. var oldPush = array.push;
  34578. array.push = function () {
  34579. var items = [];
  34580. for (var _i = 0; _i < arguments.length; _i++) {
  34581. items[_i] = arguments[_i];
  34582. }
  34583. var result = oldPush.apply(array, items);
  34584. _this._markAllSubMeshesAsTexturesDirty();
  34585. return result;
  34586. };
  34587. var oldSplice = array.splice;
  34588. array.splice = function (index, deleteCount) {
  34589. var deleted = oldSplice.apply(array, [index, deleteCount]);
  34590. _this._markAllSubMeshesAsTexturesDirty();
  34591. return deleted;
  34592. };
  34593. };
  34594. // Properties
  34595. MultiMaterial.prototype.getSubMaterial = function (index) {
  34596. if (index < 0 || index >= this.subMaterials.length) {
  34597. return this.getScene().defaultMaterial;
  34598. }
  34599. return this.subMaterials[index];
  34600. };
  34601. MultiMaterial.prototype.getActiveTextures = function () {
  34602. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  34603. var _a;
  34604. };
  34605. // Methods
  34606. MultiMaterial.prototype.getClassName = function () {
  34607. return "MultiMaterial";
  34608. };
  34609. MultiMaterial.prototype.isReady = function (mesh) {
  34610. for (var index = 0; index < this.subMaterials.length; index++) {
  34611. var subMaterial = this.subMaterials[index];
  34612. if (subMaterial) {
  34613. if (!this.subMaterials[index].isReady(mesh)) {
  34614. return false;
  34615. }
  34616. }
  34617. }
  34618. return true;
  34619. };
  34620. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  34621. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  34622. for (var index = 0; index < this.subMaterials.length; index++) {
  34623. var subMaterial = null;
  34624. if (cloneChildren) {
  34625. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  34626. }
  34627. else {
  34628. subMaterial = this.subMaterials[index];
  34629. }
  34630. newMultiMaterial.subMaterials.push(subMaterial);
  34631. }
  34632. return newMultiMaterial;
  34633. };
  34634. MultiMaterial.prototype.serialize = function () {
  34635. var serializationObject = {};
  34636. serializationObject.name = this.name;
  34637. serializationObject.id = this.id;
  34638. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34639. serializationObject.materials = [];
  34640. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  34641. var subMat = this.subMaterials[matIndex];
  34642. if (subMat) {
  34643. serializationObject.materials.push(subMat.id);
  34644. }
  34645. else {
  34646. serializationObject.materials.push(null);
  34647. }
  34648. }
  34649. return serializationObject;
  34650. };
  34651. return MultiMaterial;
  34652. }(BABYLON.Material));
  34653. BABYLON.MultiMaterial = MultiMaterial;
  34654. })(BABYLON || (BABYLON = {}));
  34655. //# sourceMappingURL=babylon.multiMaterial.js.map
  34656. var BABYLON;
  34657. (function (BABYLON) {
  34658. var PBRMaterialDefines = (function (_super) {
  34659. __extends(PBRMaterialDefines, _super);
  34660. function PBRMaterialDefines() {
  34661. var _this = _super.call(this) || this;
  34662. _this.PBR = true;
  34663. _this.ALBEDO = false;
  34664. _this.AMBIENT = false;
  34665. _this.AMBIENTINGRAYSCALE = false;
  34666. _this.OPACITY = false;
  34667. _this.OPACITYRGB = false;
  34668. _this.REFLECTION = false;
  34669. _this.EMISSIVE = false;
  34670. _this.REFLECTIVITY = false;
  34671. _this.BUMP = false;
  34672. _this.PARALLAX = false;
  34673. _this.PARALLAXOCCLUSION = false;
  34674. _this.SPECULAROVERALPHA = false;
  34675. _this.CLIPPLANE = false;
  34676. _this.ALPHATEST = false;
  34677. _this.ALPHABLEND = false;
  34678. _this.ALPHAFROMALBEDO = false;
  34679. _this.POINTSIZE = false;
  34680. _this.FOG = false;
  34681. _this.SPECULARTERM = false;
  34682. _this.NORMAL = false;
  34683. _this.TANGENT = false;
  34684. _this.UV1 = false;
  34685. _this.UV2 = false;
  34686. _this.VERTEXCOLOR = false;
  34687. _this.VERTEXALPHA = false;
  34688. _this.NUM_BONE_INFLUENCERS = 0;
  34689. _this.BonesPerMesh = 0;
  34690. _this.INSTANCES = false;
  34691. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34692. _this.MICROSURFACEAUTOMATIC = false;
  34693. _this.LIGHTMAP = false;
  34694. _this.USELIGHTMAPASSHADOWMAP = false;
  34695. _this.REFLECTIONMAP_3D = false;
  34696. _this.REFLECTIONMAP_SPHERICAL = false;
  34697. _this.REFLECTIONMAP_PLANAR = false;
  34698. _this.REFLECTIONMAP_CUBIC = false;
  34699. _this.REFLECTIONMAP_PROJECTION = false;
  34700. _this.REFLECTIONMAP_SKYBOX = false;
  34701. _this.REFLECTIONMAP_EXPLICIT = false;
  34702. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34703. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34704. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34705. _this.INVERTCUBICMAP = false;
  34706. _this.LOGARITHMICDEPTH = false;
  34707. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34708. _this.REFRACTION = false;
  34709. _this.REFRACTIONMAP_3D = false;
  34710. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34711. _this.REFRACTIONMAPINLINEARSPACE = false;
  34712. _this.LODBASEDMICROSFURACE = false;
  34713. _this.USEPHYSICALLIGHTFALLOFF = false;
  34714. _this.RADIANCEOVERALPHA = false;
  34715. _this.USEPMREMREFLECTION = false;
  34716. _this.USEPMREMREFRACTION = false;
  34717. _this.INVERTNORMALMAPX = false;
  34718. _this.INVERTNORMALMAPY = false;
  34719. _this.TWOSIDEDLIGHTING = false;
  34720. _this.SHADOWFLOAT = false;
  34721. _this.NORMALXYSCALE = true;
  34722. _this.USERIGHTHANDEDSYSTEM = false;
  34723. _this.METALLICWORKFLOW = false;
  34724. _this.METALLICMAP = false;
  34725. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34726. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34727. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34728. _this.AOSTOREINMETALMAPRED = false;
  34729. _this.MICROSURFACEMAP = false;
  34730. _this.MORPHTARGETS = false;
  34731. _this.MORPHTARGETS_NORMAL = false;
  34732. _this.MORPHTARGETS_TANGENT = false;
  34733. _this.NUM_MORPH_INFLUENCERS = 0;
  34734. _this.ALPHATESTVALUE = 0.5;
  34735. _this.PREMULTIPLYALPHA = false;
  34736. _this.ALPHAFRESNEL = false;
  34737. _this.IMAGEPROCESSING = false;
  34738. _this.VIGNETTE = false;
  34739. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34740. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34741. _this.TONEMAPPING = false;
  34742. _this.CONTRAST = false;
  34743. _this.COLORCURVES = false;
  34744. _this.COLORGRADING = false;
  34745. _this.SAMPLER3DGREENDEPTH = false;
  34746. _this.SAMPLER3DBGRMAP = false;
  34747. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34748. _this.EXPOSURE = false;
  34749. _this.rebuild();
  34750. return _this;
  34751. }
  34752. PBRMaterialDefines.prototype.reset = function () {
  34753. _super.prototype.reset.call(this);
  34754. this.ALPHATESTVALUE = 0.5;
  34755. this.PBR = true;
  34756. };
  34757. return PBRMaterialDefines;
  34758. }(BABYLON.MaterialDefines));
  34759. /**
  34760. * The Physically based material base class of BJS.
  34761. *
  34762. * This offers the main features of a standard PBR material.
  34763. * For more information, please refer to the documentation :
  34764. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34765. */
  34766. var PBRBaseMaterial = (function (_super) {
  34767. __extends(PBRBaseMaterial, _super);
  34768. /**
  34769. * Instantiates a new PBRMaterial instance.
  34770. *
  34771. * @param name The material name
  34772. * @param scene The scene the material will be use in.
  34773. */
  34774. function PBRBaseMaterial(name, scene) {
  34775. var _this = _super.call(this, name, scene) || this;
  34776. /**
  34777. * Intensity of the direct lights e.g. the four lights available in your scene.
  34778. * This impacts both the direct diffuse and specular highlights.
  34779. */
  34780. _this._directIntensity = 1.0;
  34781. /**
  34782. * Intensity of the emissive part of the material.
  34783. * This helps controlling the emissive effect without modifying the emissive color.
  34784. */
  34785. _this._emissiveIntensity = 1.0;
  34786. /**
  34787. * Intensity of the environment e.g. how much the environment will light the object
  34788. * either through harmonics for rough material or through the refelction for shiny ones.
  34789. */
  34790. _this._environmentIntensity = 1.0;
  34791. /**
  34792. * This is a special control allowing the reduction of the specular highlights coming from the
  34793. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34794. */
  34795. _this._specularIntensity = 1.0;
  34796. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34797. /**
  34798. * Debug Control allowing disabling the bump map on this material.
  34799. */
  34800. _this._disableBumpMap = false;
  34801. /**
  34802. * AKA Occlusion Texture Intensity in other nomenclature.
  34803. */
  34804. _this._ambientTextureStrength = 1.0;
  34805. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  34806. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34807. /**
  34808. * AKA Diffuse Color in other nomenclature.
  34809. */
  34810. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34811. /**
  34812. * AKA Specular Color in other nomenclature.
  34813. */
  34814. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34815. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  34816. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34817. /**
  34818. * AKA Glossiness in other nomenclature.
  34819. */
  34820. _this._microSurface = 0.9;
  34821. /**
  34822. * source material index of refraction (IOR)' / 'destination material IOR.
  34823. */
  34824. _this._indexOfRefraction = 0.66;
  34825. /**
  34826. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34827. */
  34828. _this._invertRefractionY = false;
  34829. /**
  34830. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34831. * Materials half opaque for instance using refraction could benefit from this control.
  34832. */
  34833. _this._linkRefractionWithTransparency = false;
  34834. _this._useLightmapAsShadowmap = false;
  34835. /**
  34836. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34837. */
  34838. _this._useAlphaFromAlbedoTexture = false;
  34839. /**
  34840. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34841. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34842. */
  34843. _this._useSpecularOverAlpha = true;
  34844. /**
  34845. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34846. */
  34847. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34848. /**
  34849. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34850. */
  34851. _this._useRoughnessFromMetallicTextureAlpha = true;
  34852. /**
  34853. * Specifies if the metallic texture contains the roughness information in its green channel.
  34854. */
  34855. _this._useRoughnessFromMetallicTextureGreen = false;
  34856. /**
  34857. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34858. */
  34859. _this._useMetallnessFromMetallicTextureBlue = false;
  34860. /**
  34861. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34862. */
  34863. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34864. /**
  34865. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34866. */
  34867. _this._useAmbientInGrayScale = false;
  34868. /**
  34869. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34870. * The material will try to infer what glossiness each pixel should be.
  34871. */
  34872. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34873. /**
  34874. * BJS is using an harcoded light falloff based on a manually sets up range.
  34875. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34876. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34877. */
  34878. _this._usePhysicalLightFalloff = true;
  34879. /**
  34880. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34881. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34882. */
  34883. _this._useRadianceOverAlpha = true;
  34884. /**
  34885. * Allows using the bump map in parallax mode.
  34886. */
  34887. _this._useParallax = false;
  34888. /**
  34889. * Allows using the bump map in parallax occlusion mode.
  34890. */
  34891. _this._useParallaxOcclusion = false;
  34892. /**
  34893. * Controls the scale bias of the parallax mode.
  34894. */
  34895. _this._parallaxScaleBias = 0.05;
  34896. /**
  34897. * If sets to true, disables all the lights affecting the material.
  34898. */
  34899. _this._disableLighting = false;
  34900. /**
  34901. * Number of Simultaneous lights allowed on the material.
  34902. */
  34903. _this._maxSimultaneousLights = 4;
  34904. /**
  34905. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34906. */
  34907. _this._invertNormalMapX = false;
  34908. /**
  34909. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34910. */
  34911. _this._invertNormalMapY = false;
  34912. /**
  34913. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34914. */
  34915. _this._twoSidedLighting = false;
  34916. /**
  34917. * Defines the alpha limits in alpha test mode.
  34918. */
  34919. _this._alphaCutOff = 0.4;
  34920. /**
  34921. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34922. */
  34923. _this._forceAlphaTest = false;
  34924. /**
  34925. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  34926. * in your scene composition.
  34927. */
  34928. _this._premultiplyAlpha = false;
  34929. /**
  34930. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34931. * And/Or occlude the blended part.
  34932. */
  34933. _this._useAlphaFresnel = false;
  34934. _this._renderTargets = new BABYLON.SmartArray(16);
  34935. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34936. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34937. _this._tempColor = new BABYLON.Color3();
  34938. // Setup the default processing configuration to the scene.
  34939. _this._attachImageProcessingConfiguration(null);
  34940. _this.getRenderTargetTextures = function () {
  34941. _this._renderTargets.reset();
  34942. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34943. _this._renderTargets.push(_this._reflectionTexture);
  34944. }
  34945. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34946. _this._renderTargets.push(_this._refractionTexture);
  34947. }
  34948. return _this._renderTargets;
  34949. };
  34950. return _this;
  34951. }
  34952. /**
  34953. * Attaches a new image processing configuration to the PBR Material.
  34954. * @param configuration
  34955. */
  34956. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34957. var _this = this;
  34958. if (configuration === this._imageProcessingConfiguration) {
  34959. return;
  34960. }
  34961. // Detaches observer.
  34962. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34963. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34964. }
  34965. // Pick the scene configuration if needed.
  34966. if (!configuration) {
  34967. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34968. }
  34969. else {
  34970. this._imageProcessingConfiguration = configuration;
  34971. }
  34972. // Attaches observer.
  34973. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34974. _this._markAllSubMeshesAsImageProcessingDirty();
  34975. });
  34976. };
  34977. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34978. get: function () {
  34979. return this._useLogarithmicDepth;
  34980. },
  34981. set: function (value) {
  34982. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34983. },
  34984. enumerable: true,
  34985. configurable: true
  34986. });
  34987. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34988. if (this._linkRefractionWithTransparency) {
  34989. return false;
  34990. }
  34991. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34992. };
  34993. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34994. if (this._forceAlphaTest) {
  34995. return true;
  34996. }
  34997. if (this._linkRefractionWithTransparency) {
  34998. return false;
  34999. }
  35000. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  35001. };
  35002. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35003. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  35004. };
  35005. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35006. return this._albedoTexture;
  35007. };
  35008. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35009. if (this.isFrozen) {
  35010. if (this._wasPreviouslyReady) {
  35011. return true;
  35012. }
  35013. }
  35014. if (!subMesh._materialDefines) {
  35015. subMesh._materialDefines = new PBRMaterialDefines();
  35016. }
  35017. var scene = this.getScene();
  35018. var defines = subMesh._materialDefines;
  35019. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35020. if (defines._renderId === scene.getRenderId()) {
  35021. return true;
  35022. }
  35023. }
  35024. var engine = scene.getEngine();
  35025. // Lights
  35026. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35027. defines._needNormals = true;
  35028. // Textures
  35029. if (defines._areTexturesDirty) {
  35030. defines._needUVs = false;
  35031. if (scene.texturesEnabled) {
  35032. if (scene.getEngine().getCaps().textureLOD) {
  35033. defines.LODBASEDMICROSFURACE = true;
  35034. }
  35035. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35036. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35037. return false;
  35038. }
  35039. defines._needUVs = true;
  35040. defines.ALBEDO = true;
  35041. }
  35042. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35043. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35044. return false;
  35045. }
  35046. defines._needUVs = true;
  35047. defines.AMBIENT = true;
  35048. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35049. }
  35050. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35051. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35052. return false;
  35053. }
  35054. defines._needUVs = true;
  35055. defines.OPACITY = true;
  35056. if (this._opacityTexture.getAlphaFromRGB) {
  35057. defines.OPACITYRGB = true;
  35058. }
  35059. }
  35060. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  35061. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35062. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35063. return false;
  35064. }
  35065. defines.REFLECTION = true;
  35066. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35067. defines.INVERTCUBICMAP = true;
  35068. }
  35069. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35070. switch (reflectionTexture.coordinatesMode) {
  35071. case BABYLON.Texture.CUBIC_MODE:
  35072. case BABYLON.Texture.INVCUBIC_MODE:
  35073. defines.REFLECTIONMAP_CUBIC = true;
  35074. break;
  35075. case BABYLON.Texture.EXPLICIT_MODE:
  35076. defines.REFLECTIONMAP_EXPLICIT = true;
  35077. break;
  35078. case BABYLON.Texture.PLANAR_MODE:
  35079. defines.REFLECTIONMAP_PLANAR = true;
  35080. break;
  35081. case BABYLON.Texture.PROJECTION_MODE:
  35082. defines.REFLECTIONMAP_PROJECTION = true;
  35083. break;
  35084. case BABYLON.Texture.SKYBOX_MODE:
  35085. defines.REFLECTIONMAP_SKYBOX = true;
  35086. break;
  35087. case BABYLON.Texture.SPHERICAL_MODE:
  35088. defines.REFLECTIONMAP_SPHERICAL = true;
  35089. break;
  35090. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35091. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35092. break;
  35093. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35094. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35095. break;
  35096. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35097. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35098. break;
  35099. }
  35100. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  35101. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35102. if (reflectionTexture.isPMREM) {
  35103. defines.USEPMREMREFLECTION = true;
  35104. }
  35105. }
  35106. }
  35107. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35108. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35109. return false;
  35110. }
  35111. defines._needUVs = true;
  35112. defines.LIGHTMAP = true;
  35113. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35114. }
  35115. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35116. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35117. return false;
  35118. }
  35119. defines._needUVs = true;
  35120. defines.EMISSIVE = true;
  35121. }
  35122. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35123. if (this._metallicTexture) {
  35124. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35125. return false;
  35126. }
  35127. defines._needUVs = true;
  35128. defines.METALLICWORKFLOW = true;
  35129. defines.METALLICMAP = true;
  35130. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35131. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35132. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35133. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35134. }
  35135. else if (this._reflectivityTexture) {
  35136. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35137. return false;
  35138. }
  35139. defines._needUVs = true;
  35140. defines.REFLECTIVITY = true;
  35141. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35142. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35143. }
  35144. if (this._microSurfaceTexture) {
  35145. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35146. return false;
  35147. }
  35148. defines._needUVs = true;
  35149. defines.MICROSURFACEMAP = true;
  35150. }
  35151. }
  35152. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35153. // Bump texure can not be none blocking.
  35154. if (!this._bumpTexture.isReady()) {
  35155. return false;
  35156. }
  35157. defines._needUVs = true;
  35158. defines.BUMP = true;
  35159. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35160. defines.PARALLAX = true;
  35161. if (this._useParallaxOcclusion) {
  35162. defines.PARALLAXOCCLUSION = true;
  35163. }
  35164. }
  35165. if (this._invertNormalMapX) {
  35166. defines.INVERTNORMALMAPX = true;
  35167. }
  35168. if (this._invertNormalMapY) {
  35169. defines.INVERTNORMALMAPY = true;
  35170. }
  35171. if (scene._mirroredCameraPosition) {
  35172. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  35173. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  35174. }
  35175. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  35176. }
  35177. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35178. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35179. return false;
  35180. }
  35181. defines._needUVs = true;
  35182. defines.REFRACTION = true;
  35183. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35184. if (this._linkRefractionWithTransparency) {
  35185. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35186. }
  35187. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  35188. defines.REFRACTIONMAPINLINEARSPACE = true;
  35189. if (this._refractionTexture.isPMREM) {
  35190. defines.USEPMREMREFRACTION = true;
  35191. }
  35192. }
  35193. }
  35194. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35195. defines.ALPHAFROMALBEDO = true;
  35196. }
  35197. }
  35198. if (this._useSpecularOverAlpha) {
  35199. defines.SPECULAROVERALPHA = true;
  35200. }
  35201. if (this._usePhysicalLightFalloff) {
  35202. defines.USEPHYSICALLIGHTFALLOFF = true;
  35203. }
  35204. if (this._useRadianceOverAlpha) {
  35205. defines.RADIANCEOVERALPHA = true;
  35206. }
  35207. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35208. defines.METALLICWORKFLOW = true;
  35209. }
  35210. if (!this.backFaceCulling && this._twoSidedLighting) {
  35211. defines.TWOSIDEDLIGHTING = true;
  35212. }
  35213. defines.ALPHATESTVALUE = this._alphaCutOff;
  35214. defines.PREMULTIPLYALPHA = this._premultiplyAlpha;
  35215. defines.ALPHABLEND = this.needAlphaBlending();
  35216. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35217. }
  35218. if (defines._areImageProcessingDirty) {
  35219. if (!this._imageProcessingConfiguration.isReady()) {
  35220. return false;
  35221. }
  35222. this._imageProcessingConfiguration.prepareDefines(defines);
  35223. }
  35224. // Misc.
  35225. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35226. // Values that need to be evaluated on every frame
  35227. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  35228. // Attribs
  35229. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35230. if (mesh) {
  35231. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35232. mesh.createNormals(true);
  35233. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35234. }
  35235. }
  35236. }
  35237. // Get correct effect
  35238. if (defines.isDirty) {
  35239. defines.markAsProcessed();
  35240. scene.resetCachedMaterial();
  35241. // Fallbacks
  35242. var fallbacks = new BABYLON.EffectFallbacks();
  35243. if (defines.REFLECTION) {
  35244. fallbacks.addFallback(0, "REFLECTION");
  35245. }
  35246. if (defines.REFRACTION) {
  35247. fallbacks.addFallback(0, "REFRACTION");
  35248. }
  35249. if (defines.REFLECTIVITY) {
  35250. fallbacks.addFallback(0, "REFLECTIVITY");
  35251. }
  35252. if (defines.BUMP) {
  35253. fallbacks.addFallback(0, "BUMP");
  35254. }
  35255. if (defines.PARALLAX) {
  35256. fallbacks.addFallback(1, "PARALLAX");
  35257. }
  35258. if (defines.PARALLAXOCCLUSION) {
  35259. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35260. }
  35261. if (defines.SPECULAROVERALPHA) {
  35262. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35263. }
  35264. if (defines.FOG) {
  35265. fallbacks.addFallback(1, "FOG");
  35266. }
  35267. if (defines.POINTSIZE) {
  35268. fallbacks.addFallback(0, "POINTSIZE");
  35269. }
  35270. if (defines.LOGARITHMICDEPTH) {
  35271. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35272. }
  35273. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35274. if (defines.SPECULARTERM) {
  35275. fallbacks.addFallback(0, "SPECULARTERM");
  35276. }
  35277. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35278. fallbacks.addCPUSkinningFallback(0, mesh);
  35279. }
  35280. //Attributes
  35281. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35282. if (defines.NORMAL) {
  35283. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35284. }
  35285. if (defines.TANGENT) {
  35286. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35287. }
  35288. if (defines.UV1) {
  35289. attribs.push(BABYLON.VertexBuffer.UVKind);
  35290. }
  35291. if (defines.UV2) {
  35292. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35293. }
  35294. if (defines.VERTEXCOLOR) {
  35295. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35296. }
  35297. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35298. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35299. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35300. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35301. "vFogInfos", "vFogColor", "pointSize",
  35302. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35303. "mBones",
  35304. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35305. "vLightingIntensity",
  35306. "logarithmicDepthConstant",
  35307. "vSphericalX", "vSphericalY", "vSphericalZ",
  35308. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35309. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35310. "vMicrosurfaceTextureLods"
  35311. ];
  35312. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35313. var uniformBuffers = ["Material", "Scene"];
  35314. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35315. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35316. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35317. uniformsNames: uniforms,
  35318. uniformBuffersNames: uniformBuffers,
  35319. samplers: samplers,
  35320. defines: defines,
  35321. maxSimultaneousLights: this._maxSimultaneousLights
  35322. });
  35323. var onCompiled = function (effect) {
  35324. if (this.onCompiled) {
  35325. this.onCompiled(effect);
  35326. }
  35327. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35328. }.bind(this);
  35329. var join = defines.toString();
  35330. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35331. attributes: attribs,
  35332. uniformsNames: uniforms,
  35333. uniformBuffersNames: uniformBuffers,
  35334. samplers: samplers,
  35335. defines: join,
  35336. fallbacks: fallbacks,
  35337. onCompiled: onCompiled,
  35338. onError: this.onError,
  35339. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35340. }, engine), defines);
  35341. this.buildUniformLayout();
  35342. }
  35343. if (!subMesh.effect.isReady()) {
  35344. return false;
  35345. }
  35346. defines._renderId = scene.getRenderId();
  35347. this._wasPreviouslyReady = true;
  35348. return true;
  35349. };
  35350. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35351. // Order is important !
  35352. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35353. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35354. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35355. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35356. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35357. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35358. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35359. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35360. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35361. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35362. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35363. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35364. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35365. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35366. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35367. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35368. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35369. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35370. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35371. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35372. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35373. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35374. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35375. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  35376. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35377. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35378. this._uniformBuffer.addUniform("pointSize", 1);
  35379. this._uniformBuffer.create();
  35380. };
  35381. PBRBaseMaterial.prototype.unbind = function () {
  35382. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35383. this._uniformBuffer.setTexture("reflection2DSampler", null);
  35384. }
  35385. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35386. this._uniformBuffer.setTexture("refraction2DSampler", null);
  35387. }
  35388. _super.prototype.unbind.call(this);
  35389. };
  35390. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35391. this._activeEffect.setMatrix("world", world);
  35392. };
  35393. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35394. var scene = this.getScene();
  35395. var defines = subMesh._materialDefines;
  35396. if (!defines) {
  35397. return;
  35398. }
  35399. var effect = subMesh.effect;
  35400. this._activeEffect = effect;
  35401. // Matrices
  35402. this.bindOnlyWorldMatrix(world);
  35403. // Bones
  35404. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35405. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35406. this._uniformBuffer.bindToEffect(effect, "Material");
  35407. this.bindViewProjection(effect);
  35408. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35409. // Texture uniforms
  35410. if (scene.texturesEnabled) {
  35411. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35412. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35413. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  35414. }
  35415. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35416. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35417. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35418. }
  35419. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35420. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35421. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35422. }
  35423. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  35424. ;
  35425. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35426. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  35427. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35428. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35429. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35430. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  35431. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  35432. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  35433. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  35434. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  35435. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  35436. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  35437. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  35438. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  35439. }
  35440. }
  35441. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35442. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35443. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35444. }
  35445. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35446. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35447. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35448. }
  35449. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35450. if (this._metallicTexture) {
  35451. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35452. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  35453. }
  35454. else if (this._reflectivityTexture) {
  35455. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35456. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  35457. }
  35458. if (this._microSurfaceTexture) {
  35459. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35460. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  35461. }
  35462. }
  35463. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35464. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35465. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35466. }
  35467. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35468. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  35469. var depth = 1.0;
  35470. if (!this._refractionTexture.isCube) {
  35471. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35472. if (this._refractionTexture.depth) {
  35473. depth = this._refractionTexture.depth;
  35474. }
  35475. }
  35476. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35477. }
  35478. if ((reflectionTexture || this._refractionTexture)) {
  35479. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  35480. }
  35481. }
  35482. // Point size
  35483. if (this.pointsCloud) {
  35484. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35485. }
  35486. // Colors
  35487. if (defines.METALLICWORKFLOW) {
  35488. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35489. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35490. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35491. }
  35492. else {
  35493. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35494. }
  35495. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35496. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35497. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35498. // Misc
  35499. this._lightingInfos.x = this._directIntensity;
  35500. this._lightingInfos.y = this._emissiveIntensity;
  35501. this._lightingInfos.z = this._environmentIntensity;
  35502. this._lightingInfos.w = this._specularIntensity;
  35503. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35504. }
  35505. // Textures
  35506. if (scene.texturesEnabled) {
  35507. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35508. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35509. }
  35510. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35511. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35512. }
  35513. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35514. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35515. }
  35516. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35517. if (reflectionTexture.isCube) {
  35518. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  35519. }
  35520. else {
  35521. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  35522. }
  35523. }
  35524. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35525. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35526. }
  35527. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35528. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35529. }
  35530. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35531. if (this._metallicTexture) {
  35532. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35533. }
  35534. else if (this._reflectivityTexture) {
  35535. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35536. }
  35537. if (this._microSurfaceTexture) {
  35538. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35539. }
  35540. }
  35541. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35542. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35543. }
  35544. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35545. if (this._refractionTexture.isCube) {
  35546. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  35547. }
  35548. else {
  35549. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  35550. }
  35551. }
  35552. }
  35553. // Clip plane
  35554. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35555. // Colors
  35556. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35557. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35558. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35559. }
  35560. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35561. // Lights
  35562. if (scene.lightsEnabled && !this._disableLighting) {
  35563. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35564. }
  35565. // View
  35566. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35567. this.bindView(effect);
  35568. }
  35569. // Fog
  35570. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35571. // Morph targets
  35572. if (defines.NUM_MORPH_INFLUENCERS) {
  35573. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35574. }
  35575. // image processing
  35576. this._imageProcessingConfiguration.bind(this._activeEffect);
  35577. // Log. depth
  35578. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35579. }
  35580. this._uniformBuffer.update();
  35581. this._afterBind(mesh);
  35582. scene = null;
  35583. };
  35584. PBRBaseMaterial.prototype.getAnimatables = function () {
  35585. var results = [];
  35586. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35587. results.push(this._albedoTexture);
  35588. }
  35589. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35590. results.push(this._ambientTexture);
  35591. }
  35592. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35593. results.push(this._opacityTexture);
  35594. }
  35595. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35596. results.push(this._reflectionTexture);
  35597. }
  35598. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35599. results.push(this._emissiveTexture);
  35600. }
  35601. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35602. results.push(this._metallicTexture);
  35603. }
  35604. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35605. results.push(this._reflectivityTexture);
  35606. }
  35607. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35608. results.push(this._bumpTexture);
  35609. }
  35610. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35611. results.push(this._lightmapTexture);
  35612. }
  35613. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35614. results.push(this._refractionTexture);
  35615. }
  35616. return results;
  35617. };
  35618. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35619. if (forceDisposeTextures) {
  35620. if (this._albedoTexture) {
  35621. this._albedoTexture.dispose();
  35622. }
  35623. if (this._ambientTexture) {
  35624. this._ambientTexture.dispose();
  35625. }
  35626. if (this._opacityTexture) {
  35627. this._opacityTexture.dispose();
  35628. }
  35629. if (this._reflectionTexture) {
  35630. this._reflectionTexture.dispose();
  35631. }
  35632. if (this._emissiveTexture) {
  35633. this._emissiveTexture.dispose();
  35634. }
  35635. if (this._metallicTexture) {
  35636. this._metallicTexture.dispose();
  35637. }
  35638. if (this._reflectivityTexture) {
  35639. this._reflectivityTexture.dispose();
  35640. }
  35641. if (this._bumpTexture) {
  35642. this._bumpTexture.dispose();
  35643. }
  35644. if (this._lightmapTexture) {
  35645. this._lightmapTexture.dispose();
  35646. }
  35647. if (this._refractionTexture) {
  35648. this._refractionTexture.dispose();
  35649. }
  35650. }
  35651. this._renderTargets.dispose();
  35652. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35653. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35654. }
  35655. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35656. };
  35657. return PBRBaseMaterial;
  35658. }(BABYLON.PushMaterial));
  35659. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35660. __decorate([
  35661. BABYLON.serializeAsImageProcessingConfiguration()
  35662. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35663. __decorate([
  35664. BABYLON.serialize()
  35665. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35666. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35667. })(BABYLON || (BABYLON = {}));
  35668. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35669. var BABYLON;
  35670. (function (BABYLON) {
  35671. var Internals;
  35672. (function (Internals) {
  35673. /**
  35674. * The Physically based simple base material of BJS.
  35675. *
  35676. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35677. * It is used as the base class for both the specGloss and metalRough conventions.
  35678. */
  35679. var PBRBaseSimpleMaterial = (function (_super) {
  35680. __extends(PBRBaseSimpleMaterial, _super);
  35681. /**
  35682. * Instantiates a new PBRMaterial instance.
  35683. *
  35684. * @param name The material name
  35685. * @param scene The scene the material will be use in.
  35686. */
  35687. function PBRBaseSimpleMaterial(name, scene) {
  35688. var _this = _super.call(this, name, scene) || this;
  35689. /**
  35690. * Number of Simultaneous lights allowed on the material.
  35691. */
  35692. _this.maxSimultaneousLights = 4;
  35693. /**
  35694. * If sets to true, disables all the lights affecting the material.
  35695. */
  35696. _this.disableLighting = false;
  35697. /**
  35698. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35699. */
  35700. _this.invertNormalMapX = false;
  35701. /**
  35702. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35703. */
  35704. _this.invertNormalMapY = false;
  35705. /**
  35706. * Emissivie color used to self-illuminate the model.
  35707. */
  35708. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35709. /**
  35710. * Occlusion Channel Strenght.
  35711. */
  35712. _this.occlusionStrength = 1.0;
  35713. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35714. _this._useAmbientInGrayScale = true;
  35715. return _this;
  35716. }
  35717. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35718. /**
  35719. * Gets the current transparency mode.
  35720. */
  35721. get: function () {
  35722. return this._transparencyMode;
  35723. },
  35724. /**
  35725. * Sets the transparency mode of the material.
  35726. */
  35727. set: function (value) {
  35728. if (this._transparencyMode === value) {
  35729. return;
  35730. }
  35731. this._transparencyMode = value;
  35732. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35733. this._forceAlphaTest = true;
  35734. }
  35735. else {
  35736. this._forceAlphaTest = false;
  35737. }
  35738. this._markAllSubMeshesAsTexturesDirty();
  35739. },
  35740. enumerable: true,
  35741. configurable: true
  35742. });
  35743. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35744. /**
  35745. * Gets the current double sided mode.
  35746. */
  35747. get: function () {
  35748. return this._twoSidedLighting;
  35749. },
  35750. /**
  35751. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35752. */
  35753. set: function (value) {
  35754. if (this._twoSidedLighting === value) {
  35755. return;
  35756. }
  35757. this._twoSidedLighting = value;
  35758. this.backFaceCulling = !value;
  35759. this._markAllSubMeshesAsTexturesDirty();
  35760. },
  35761. enumerable: true,
  35762. configurable: true
  35763. });
  35764. /**
  35765. * Specifies wether or not the alpha value of the albedo texture should be used.
  35766. */
  35767. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35768. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35769. };
  35770. /**
  35771. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35772. */
  35773. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35774. if (this._linkRefractionWithTransparency) {
  35775. return false;
  35776. }
  35777. return (this.alpha < 1.0) ||
  35778. (this._shouldUseAlphaFromAlbedoTexture() &&
  35779. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35780. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35781. };
  35782. /**
  35783. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35784. */
  35785. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35786. if (this._linkRefractionWithTransparency) {
  35787. return false;
  35788. }
  35789. return this._shouldUseAlphaFromAlbedoTexture() &&
  35790. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35791. };
  35792. return PBRBaseSimpleMaterial;
  35793. }(BABYLON.PBRBaseMaterial));
  35794. __decorate([
  35795. BABYLON.serialize(),
  35796. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35797. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35798. __decorate([
  35799. BABYLON.serialize(),
  35800. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35801. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35802. __decorate([
  35803. BABYLON.serializeAsTexture(),
  35804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35805. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35806. __decorate([
  35807. BABYLON.serialize(),
  35808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35809. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35810. __decorate([
  35811. BABYLON.serialize(),
  35812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35813. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35814. __decorate([
  35815. BABYLON.serializeAsTexture(),
  35816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35817. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35818. __decorate([
  35819. BABYLON.serializeAsColor3("emissive"),
  35820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35821. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35822. __decorate([
  35823. BABYLON.serializeAsTexture(),
  35824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35825. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35826. __decorate([
  35827. BABYLON.serialize(),
  35828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35829. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35830. __decorate([
  35831. BABYLON.serializeAsTexture(),
  35832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35833. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35834. __decorate([
  35835. BABYLON.serialize(),
  35836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35837. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35838. __decorate([
  35839. BABYLON.serialize()
  35840. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35841. __decorate([
  35842. BABYLON.serialize()
  35843. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35844. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35845. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35846. })(BABYLON || (BABYLON = {}));
  35847. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35848. var BABYLON;
  35849. (function (BABYLON) {
  35850. /**
  35851. * The Physically based material of BJS.
  35852. *
  35853. * This offers the main features of a standard PBR material.
  35854. * For more information, please refer to the documentation :
  35855. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35856. */
  35857. var PBRMaterial = (function (_super) {
  35858. __extends(PBRMaterial, _super);
  35859. /**
  35860. * Instantiates a new PBRMaterial instance.
  35861. *
  35862. * @param name The material name
  35863. * @param scene The scene the material will be use in.
  35864. */
  35865. function PBRMaterial(name, scene) {
  35866. var _this = _super.call(this, name, scene) || this;
  35867. /**
  35868. * Intensity of the direct lights e.g. the four lights available in your scene.
  35869. * This impacts both the direct diffuse and specular highlights.
  35870. */
  35871. _this.directIntensity = 1.0;
  35872. /**
  35873. * Intensity of the emissive part of the material.
  35874. * This helps controlling the emissive effect without modifying the emissive color.
  35875. */
  35876. _this.emissiveIntensity = 1.0;
  35877. /**
  35878. * Intensity of the environment e.g. how much the environment will light the object
  35879. * either through harmonics for rough material or through the refelction for shiny ones.
  35880. */
  35881. _this.environmentIntensity = 1.0;
  35882. /**
  35883. * This is a special control allowing the reduction of the specular highlights coming from the
  35884. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35885. */
  35886. _this.specularIntensity = 1.0;
  35887. /**
  35888. * Debug Control allowing disabling the bump map on this material.
  35889. */
  35890. _this.disableBumpMap = false;
  35891. /**
  35892. * AKA Occlusion Texture Intensity in other nomenclature.
  35893. */
  35894. _this.ambientTextureStrength = 1.0;
  35895. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35896. /**
  35897. * AKA Diffuse Color in other nomenclature.
  35898. */
  35899. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35900. /**
  35901. * AKA Specular Color in other nomenclature.
  35902. */
  35903. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35904. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35905. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35906. /**
  35907. * AKA Glossiness in other nomenclature.
  35908. */
  35909. _this.microSurface = 0.9;
  35910. /**
  35911. * source material index of refraction (IOR)' / 'destination material IOR.
  35912. */
  35913. _this.indexOfRefraction = 0.66;
  35914. /**
  35915. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35916. */
  35917. _this.invertRefractionY = false;
  35918. /**
  35919. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35920. * Materials half opaque for instance using refraction could benefit from this control.
  35921. */
  35922. _this.linkRefractionWithTransparency = false;
  35923. _this.useLightmapAsShadowmap = false;
  35924. /**
  35925. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35926. */
  35927. _this.useAlphaFromAlbedoTexture = false;
  35928. /**
  35929. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35930. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35931. */
  35932. _this.useSpecularOverAlpha = true;
  35933. /**
  35934. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35935. */
  35936. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35937. /**
  35938. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35939. */
  35940. _this.useRoughnessFromMetallicTextureAlpha = true;
  35941. /**
  35942. * Specifies if the metallic texture contains the roughness information in its green channel.
  35943. */
  35944. _this.useRoughnessFromMetallicTextureGreen = false;
  35945. /**
  35946. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35947. */
  35948. _this.useMetallnessFromMetallicTextureBlue = false;
  35949. /**
  35950. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35951. */
  35952. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35953. /**
  35954. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35955. */
  35956. _this.useAmbientInGrayScale = false;
  35957. /**
  35958. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35959. * The material will try to infer what glossiness each pixel should be.
  35960. */
  35961. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35962. /**
  35963. * BJS is using an harcoded light falloff based on a manually sets up range.
  35964. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35965. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35966. */
  35967. _this.usePhysicalLightFalloff = true;
  35968. /**
  35969. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35970. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35971. */
  35972. _this.useRadianceOverAlpha = true;
  35973. /**
  35974. * Allows using the bump map in parallax mode.
  35975. */
  35976. _this.useParallax = false;
  35977. /**
  35978. * Allows using the bump map in parallax occlusion mode.
  35979. */
  35980. _this.useParallaxOcclusion = false;
  35981. /**
  35982. * Controls the scale bias of the parallax mode.
  35983. */
  35984. _this.parallaxScaleBias = 0.05;
  35985. /**
  35986. * If sets to true, disables all the lights affecting the material.
  35987. */
  35988. _this.disableLighting = false;
  35989. /**
  35990. * Number of Simultaneous lights allowed on the material.
  35991. */
  35992. _this.maxSimultaneousLights = 4;
  35993. /**
  35994. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35995. */
  35996. _this.invertNormalMapX = false;
  35997. /**
  35998. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35999. */
  36000. _this.invertNormalMapY = false;
  36001. /**
  36002. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36003. */
  36004. _this.twoSidedLighting = false;
  36005. /**
  36006. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  36007. * in your scene composition.
  36008. */
  36009. _this.premultiplyAlpha = false;
  36010. /**
  36011. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36012. * And/Or occlude the blended part.
  36013. */
  36014. _this.useAlphaFresnel = false;
  36015. return _this;
  36016. }
  36017. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36018. /**
  36019. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36020. */
  36021. get: function () {
  36022. return this._PBRMATERIAL_OPAQUE;
  36023. },
  36024. enumerable: true,
  36025. configurable: true
  36026. });
  36027. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36028. /**
  36029. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36030. */
  36031. get: function () {
  36032. return this._PBRMATERIAL_ALPHATEST;
  36033. },
  36034. enumerable: true,
  36035. configurable: true
  36036. });
  36037. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36038. /**
  36039. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36040. */
  36041. get: function () {
  36042. return this._PBRMATERIAL_ALPHABLEND;
  36043. },
  36044. enumerable: true,
  36045. configurable: true
  36046. });
  36047. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36048. /**
  36049. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36050. * They are also discarded below the alpha cutoff threshold to improve performances.
  36051. */
  36052. get: function () {
  36053. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36054. },
  36055. enumerable: true,
  36056. configurable: true
  36057. });
  36058. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36059. /**
  36060. * Gets the image processing configuration used either in this material.
  36061. */
  36062. get: function () {
  36063. return this._imageProcessingConfiguration;
  36064. },
  36065. /**
  36066. * Sets the Default image processing configuration used either in the this material.
  36067. *
  36068. * If sets to null, the scene one is in use.
  36069. */
  36070. set: function (value) {
  36071. this._attachImageProcessingConfiguration(value);
  36072. // Ensure the effect will be rebuilt.
  36073. this._markAllSubMeshesAsTexturesDirty();
  36074. },
  36075. enumerable: true,
  36076. configurable: true
  36077. });
  36078. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36079. /**
  36080. * Gets wether the color curves effect is enabled.
  36081. */
  36082. get: function () {
  36083. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36084. },
  36085. /**
  36086. * Sets wether the color curves effect is enabled.
  36087. */
  36088. set: function (value) {
  36089. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36090. },
  36091. enumerable: true,
  36092. configurable: true
  36093. });
  36094. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36095. /**
  36096. * Gets wether the color grading effect is enabled.
  36097. */
  36098. get: function () {
  36099. return this.imageProcessingConfiguration.colorGradingEnabled;
  36100. },
  36101. /**
  36102. * Gets wether the color grading effect is enabled.
  36103. */
  36104. set: function (value) {
  36105. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36106. },
  36107. enumerable: true,
  36108. configurable: true
  36109. });
  36110. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36111. /**
  36112. * Gets wether tonemapping is enabled or not.
  36113. */
  36114. get: function () {
  36115. return this._imageProcessingConfiguration.toneMappingEnabled;
  36116. },
  36117. /**
  36118. * Sets wether tonemapping is enabled or not
  36119. */
  36120. set: function (value) {
  36121. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36122. },
  36123. enumerable: true,
  36124. configurable: true
  36125. });
  36126. ;
  36127. ;
  36128. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36129. /**
  36130. * The camera exposure used on this material.
  36131. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36132. * This corresponds to a photographic exposure.
  36133. */
  36134. get: function () {
  36135. return this._imageProcessingConfiguration.exposure;
  36136. },
  36137. /**
  36138. * The camera exposure used on this material.
  36139. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36140. * This corresponds to a photographic exposure.
  36141. */
  36142. set: function (value) {
  36143. this._imageProcessingConfiguration.exposure = value;
  36144. },
  36145. enumerable: true,
  36146. configurable: true
  36147. });
  36148. ;
  36149. ;
  36150. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36151. /**
  36152. * Gets The camera contrast used on this material.
  36153. */
  36154. get: function () {
  36155. return this._imageProcessingConfiguration.contrast;
  36156. },
  36157. /**
  36158. * Sets The camera contrast used on this material.
  36159. */
  36160. set: function (value) {
  36161. this._imageProcessingConfiguration.contrast = value;
  36162. },
  36163. enumerable: true,
  36164. configurable: true
  36165. });
  36166. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36167. /**
  36168. * Gets the Color Grading 2D Lookup Texture.
  36169. */
  36170. get: function () {
  36171. return this._imageProcessingConfiguration.colorGradingTexture;
  36172. },
  36173. /**
  36174. * Sets the Color Grading 2D Lookup Texture.
  36175. */
  36176. set: function (value) {
  36177. this._imageProcessingConfiguration.colorGradingTexture = value;
  36178. },
  36179. enumerable: true,
  36180. configurable: true
  36181. });
  36182. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36183. /**
  36184. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36185. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36186. * 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;
  36187. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36188. */
  36189. get: function () {
  36190. return this._imageProcessingConfiguration.colorCurves;
  36191. },
  36192. /**
  36193. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36194. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36195. * 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;
  36196. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36197. */
  36198. set: function (value) {
  36199. this._imageProcessingConfiguration.colorCurves = value;
  36200. },
  36201. enumerable: true,
  36202. configurable: true
  36203. });
  36204. PBRMaterial.prototype.getClassName = function () {
  36205. return "PBRMaterial";
  36206. };
  36207. PBRMaterial.prototype.getActiveTextures = function () {
  36208. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36209. if (this._albedoTexture) {
  36210. activeTextures.push(this._albedoTexture);
  36211. }
  36212. if (this._ambientTexture) {
  36213. activeTextures.push(this._ambientTexture);
  36214. }
  36215. if (this._opacityTexture) {
  36216. activeTextures.push(this._opacityTexture);
  36217. }
  36218. if (this._reflectionTexture) {
  36219. activeTextures.push(this._reflectionTexture);
  36220. }
  36221. if (this._emissiveTexture) {
  36222. activeTextures.push(this._emissiveTexture);
  36223. }
  36224. if (this._reflectionTexture) {
  36225. activeTextures.push(this._reflectionTexture);
  36226. }
  36227. if (this._metallicTexture) {
  36228. activeTextures.push(this._metallicTexture);
  36229. }
  36230. if (this._microSurfaceTexture) {
  36231. activeTextures.push(this._microSurfaceTexture);
  36232. }
  36233. if (this._bumpTexture) {
  36234. activeTextures.push(this._bumpTexture);
  36235. }
  36236. if (this._lightmapTexture) {
  36237. activeTextures.push(this._lightmapTexture);
  36238. }
  36239. if (this._refractionTexture) {
  36240. activeTextures.push(this._refractionTexture);
  36241. }
  36242. return activeTextures;
  36243. };
  36244. PBRMaterial.prototype.clone = function (name) {
  36245. var _this = this;
  36246. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36247. };
  36248. PBRMaterial.prototype.serialize = function () {
  36249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36250. serializationObject.customType = "BABYLON.PBRMaterial";
  36251. return serializationObject;
  36252. };
  36253. // Statics
  36254. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36255. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36256. };
  36257. return PBRMaterial;
  36258. }(BABYLON.PBRBaseMaterial));
  36259. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36260. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36261. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36262. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36263. __decorate([
  36264. BABYLON.serialize(),
  36265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36266. ], PBRMaterial.prototype, "directIntensity", void 0);
  36267. __decorate([
  36268. BABYLON.serialize(),
  36269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36270. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36271. __decorate([
  36272. BABYLON.serialize(),
  36273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36274. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36275. __decorate([
  36276. BABYLON.serialize(),
  36277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36278. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36279. __decorate([
  36280. BABYLON.serialize(),
  36281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36282. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36283. __decorate([
  36284. BABYLON.serializeAsTexture(),
  36285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36286. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36287. __decorate([
  36288. BABYLON.serializeAsTexture(),
  36289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36290. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36291. __decorate([
  36292. BABYLON.serialize(),
  36293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36294. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36295. __decorate([
  36296. BABYLON.serializeAsTexture(),
  36297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36298. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36299. __decorate([
  36300. BABYLON.serializeAsTexture(),
  36301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36302. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36303. __decorate([
  36304. BABYLON.serializeAsTexture(),
  36305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36306. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36307. __decorate([
  36308. BABYLON.serializeAsTexture(),
  36309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36310. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36311. __decorate([
  36312. BABYLON.serializeAsTexture(),
  36313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36314. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36315. __decorate([
  36316. BABYLON.serialize(),
  36317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36318. ], PBRMaterial.prototype, "metallic", void 0);
  36319. __decorate([
  36320. BABYLON.serialize(),
  36321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36322. ], PBRMaterial.prototype, "roughness", void 0);
  36323. __decorate([
  36324. BABYLON.serializeAsTexture(),
  36325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36326. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36327. __decorate([
  36328. BABYLON.serializeAsTexture(),
  36329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36330. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36331. __decorate([
  36332. BABYLON.serializeAsTexture(),
  36333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36334. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36335. __decorate([
  36336. BABYLON.serializeAsTexture(),
  36337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36338. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36339. __decorate([
  36340. BABYLON.serializeAsColor3("ambient"),
  36341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36342. ], PBRMaterial.prototype, "ambientColor", void 0);
  36343. __decorate([
  36344. BABYLON.serializeAsColor3("albedo"),
  36345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36346. ], PBRMaterial.prototype, "albedoColor", void 0);
  36347. __decorate([
  36348. BABYLON.serializeAsColor3("reflectivity"),
  36349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36350. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36351. __decorate([
  36352. BABYLON.serializeAsColor3("reflection"),
  36353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36354. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36355. __decorate([
  36356. BABYLON.serializeAsColor3("emissive"),
  36357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36358. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36359. __decorate([
  36360. BABYLON.serialize(),
  36361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36362. ], PBRMaterial.prototype, "microSurface", void 0);
  36363. __decorate([
  36364. BABYLON.serialize(),
  36365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36366. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36367. __decorate([
  36368. BABYLON.serialize(),
  36369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36370. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36371. __decorate([
  36372. BABYLON.serialize(),
  36373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36374. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36375. __decorate([
  36376. BABYLON.serialize(),
  36377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36378. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36379. __decorate([
  36380. BABYLON.serialize(),
  36381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36382. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36383. __decorate([
  36384. BABYLON.serialize(),
  36385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36386. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36387. __decorate([
  36388. BABYLON.serialize(),
  36389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36390. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36391. __decorate([
  36392. BABYLON.serialize(),
  36393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36394. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36395. __decorate([
  36396. BABYLON.serialize(),
  36397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36398. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36399. __decorate([
  36400. BABYLON.serialize(),
  36401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36402. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36403. __decorate([
  36404. BABYLON.serialize(),
  36405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36406. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36407. __decorate([
  36408. BABYLON.serialize(),
  36409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36410. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36411. __decorate([
  36412. BABYLON.serialize(),
  36413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36414. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36415. __decorate([
  36416. BABYLON.serialize(),
  36417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36418. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36419. __decorate([
  36420. BABYLON.serialize(),
  36421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36422. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36423. __decorate([
  36424. BABYLON.serialize(),
  36425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36426. ], PBRMaterial.prototype, "useParallax", void 0);
  36427. __decorate([
  36428. BABYLON.serialize(),
  36429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36430. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36431. __decorate([
  36432. BABYLON.serialize(),
  36433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36434. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36435. __decorate([
  36436. BABYLON.serialize(),
  36437. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36438. ], PBRMaterial.prototype, "disableLighting", void 0);
  36439. __decorate([
  36440. BABYLON.serialize(),
  36441. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36442. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36443. __decorate([
  36444. BABYLON.serialize(),
  36445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36446. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36447. __decorate([
  36448. BABYLON.serialize(),
  36449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36450. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36451. __decorate([
  36452. BABYLON.serialize(),
  36453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36454. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36455. __decorate([
  36456. BABYLON.serialize(),
  36457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36458. ], PBRMaterial.prototype, "premultiplyAlpha", void 0);
  36459. __decorate([
  36460. BABYLON.serialize(),
  36461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36462. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36463. BABYLON.PBRMaterial = PBRMaterial;
  36464. })(BABYLON || (BABYLON = {}));
  36465. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36466. var BABYLON;
  36467. (function (BABYLON) {
  36468. /**
  36469. * The PBR material of BJS following the metal roughness convention.
  36470. *
  36471. * This fits to the define PBR convention in the GLTF definition:
  36472. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36473. */
  36474. var PBRMetallicRoughnessMaterial = (function (_super) {
  36475. __extends(PBRMetallicRoughnessMaterial, _super);
  36476. /**
  36477. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36478. *
  36479. * @param name The material name
  36480. * @param scene The scene the material will be use in.
  36481. */
  36482. function PBRMetallicRoughnessMaterial(name, scene) {
  36483. var _this = _super.call(this, name, scene) || this;
  36484. _this._useRoughnessFromMetallicTextureGreen = true;
  36485. _this._useMetallnessFromMetallicTextureBlue = true;
  36486. return _this;
  36487. }
  36488. /**
  36489. * Return the currrent class name of the material.
  36490. */
  36491. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36492. return "PBRMetallicRoughnessMaterial";
  36493. };
  36494. /**
  36495. * Return the active textures of the material.
  36496. */
  36497. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36498. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36499. if (this.baseTexture) {
  36500. activeTextures.push(this.baseTexture);
  36501. }
  36502. if (this.metallicRoughnessTexture) {
  36503. activeTextures.push(this.metallicRoughnessTexture);
  36504. }
  36505. return activeTextures;
  36506. };
  36507. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36508. var _this = this;
  36509. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36510. };
  36511. /**
  36512. * Serialize the material to a parsable JSON object.
  36513. */
  36514. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36515. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36516. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36517. return serializationObject;
  36518. };
  36519. /**
  36520. * Parses a JSON object correponding to the serialize function.
  36521. */
  36522. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36523. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36524. };
  36525. return PBRMetallicRoughnessMaterial;
  36526. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36527. __decorate([
  36528. BABYLON.serializeAsTexture(),
  36529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36530. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36531. __decorate([
  36532. BABYLON.serializeAsTexture(),
  36533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36534. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36535. __decorate([
  36536. BABYLON.serialize(),
  36537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36538. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36539. __decorate([
  36540. BABYLON.serialize(),
  36541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36542. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36543. __decorate([
  36544. BABYLON.serializeAsTexture(),
  36545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36546. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36547. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36548. })(BABYLON || (BABYLON = {}));
  36549. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36550. var BABYLON;
  36551. (function (BABYLON) {
  36552. /**
  36553. * The PBR material of BJS following the specular glossiness convention.
  36554. *
  36555. * This fits to the define PBR convention in the GLTF definition:
  36556. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36557. */
  36558. var PBRSpecularGlossinessMaterial = (function (_super) {
  36559. __extends(PBRSpecularGlossinessMaterial, _super);
  36560. /**
  36561. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36562. *
  36563. * @param name The material name
  36564. * @param scene The scene the material will be use in.
  36565. */
  36566. function PBRSpecularGlossinessMaterial(name, scene) {
  36567. var _this = _super.call(this, name, scene) || this;
  36568. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36569. return _this;
  36570. }
  36571. /**
  36572. * Return the currrent class name of the material.
  36573. */
  36574. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36575. return "PBRSpecularGlossinessMaterial";
  36576. };
  36577. /**
  36578. * Return the active textures of the material.
  36579. */
  36580. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36581. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36582. if (this.diffuseTexture) {
  36583. activeTextures.push(this.diffuseTexture);
  36584. }
  36585. if (this.specularGlossinessTexture) {
  36586. activeTextures.push(this.specularGlossinessTexture);
  36587. }
  36588. return activeTextures;
  36589. };
  36590. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36591. var _this = this;
  36592. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36593. };
  36594. /**
  36595. * Serialize the material to a parsable JSON object.
  36596. */
  36597. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36598. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36599. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36600. return serializationObject;
  36601. };
  36602. /**
  36603. * Parses a JSON object correponding to the serialize function.
  36604. */
  36605. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36606. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36607. };
  36608. return PBRSpecularGlossinessMaterial;
  36609. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36610. __decorate([
  36611. BABYLON.serializeAsColor3(),
  36612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36613. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36614. __decorate([
  36615. BABYLON.serializeAsTexture(),
  36616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36617. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36618. __decorate([
  36619. BABYLON.serializeAsColor3(),
  36620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36621. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36622. __decorate([
  36623. BABYLON.serialize(),
  36624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36625. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36626. __decorate([
  36627. BABYLON.serializeAsTexture(),
  36628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36629. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36630. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36631. })(BABYLON || (BABYLON = {}));
  36632. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36633. var BABYLON;
  36634. (function (BABYLON) {
  36635. var ShaderMaterial = (function (_super) {
  36636. __extends(ShaderMaterial, _super);
  36637. function ShaderMaterial(name, scene, shaderPath, options) {
  36638. var _this = _super.call(this, name, scene) || this;
  36639. _this._textures = {};
  36640. _this._textureArrays = {};
  36641. _this._floats = {};
  36642. _this._floatsArrays = {};
  36643. _this._colors3 = {};
  36644. _this._colors4 = {};
  36645. _this._vectors2 = {};
  36646. _this._vectors3 = {};
  36647. _this._vectors4 = {};
  36648. _this._matrices = {};
  36649. _this._matrices3x3 = {};
  36650. _this._matrices2x2 = {};
  36651. _this._vectors3Arrays = {};
  36652. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  36653. _this._shaderPath = shaderPath;
  36654. options.needAlphaBlending = options.needAlphaBlending || false;
  36655. options.needAlphaTesting = options.needAlphaTesting || false;
  36656. options.attributes = options.attributes || ["position", "normal", "uv"];
  36657. options.uniforms = options.uniforms || ["worldViewProjection"];
  36658. options.uniformBuffers = options.uniformBuffers || [];
  36659. options.samplers = options.samplers || [];
  36660. options.defines = options.defines || [];
  36661. _this._options = options;
  36662. return _this;
  36663. }
  36664. ShaderMaterial.prototype.getClassName = function () {
  36665. return "ShaderMaterial";
  36666. };
  36667. ShaderMaterial.prototype.needAlphaBlending = function () {
  36668. return this._options.needAlphaBlending;
  36669. };
  36670. ShaderMaterial.prototype.needAlphaTesting = function () {
  36671. return this._options.needAlphaTesting;
  36672. };
  36673. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  36674. if (this._options.uniforms.indexOf(uniformName) === -1) {
  36675. this._options.uniforms.push(uniformName);
  36676. }
  36677. };
  36678. ShaderMaterial.prototype.setTexture = function (name, texture) {
  36679. if (this._options.samplers.indexOf(name) === -1) {
  36680. this._options.samplers.push(name);
  36681. }
  36682. this._textures[name] = texture;
  36683. return this;
  36684. };
  36685. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  36686. if (this._options.samplers.indexOf(name) === -1) {
  36687. this._options.samplers.push(name);
  36688. }
  36689. this._checkUniform(name);
  36690. this._textureArrays[name] = textures;
  36691. return this;
  36692. };
  36693. ShaderMaterial.prototype.setFloat = function (name, value) {
  36694. this._checkUniform(name);
  36695. this._floats[name] = value;
  36696. return this;
  36697. };
  36698. ShaderMaterial.prototype.setFloats = function (name, value) {
  36699. this._checkUniform(name);
  36700. this._floatsArrays[name] = value;
  36701. return this;
  36702. };
  36703. ShaderMaterial.prototype.setColor3 = function (name, value) {
  36704. this._checkUniform(name);
  36705. this._colors3[name] = value;
  36706. return this;
  36707. };
  36708. ShaderMaterial.prototype.setColor4 = function (name, value) {
  36709. this._checkUniform(name);
  36710. this._colors4[name] = value;
  36711. return this;
  36712. };
  36713. ShaderMaterial.prototype.setVector2 = function (name, value) {
  36714. this._checkUniform(name);
  36715. this._vectors2[name] = value;
  36716. return this;
  36717. };
  36718. ShaderMaterial.prototype.setVector3 = function (name, value) {
  36719. this._checkUniform(name);
  36720. this._vectors3[name] = value;
  36721. return this;
  36722. };
  36723. ShaderMaterial.prototype.setVector4 = function (name, value) {
  36724. this._checkUniform(name);
  36725. this._vectors4[name] = value;
  36726. return this;
  36727. };
  36728. ShaderMaterial.prototype.setMatrix = function (name, value) {
  36729. this._checkUniform(name);
  36730. this._matrices[name] = value;
  36731. return this;
  36732. };
  36733. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  36734. this._checkUniform(name);
  36735. this._matrices3x3[name] = value;
  36736. return this;
  36737. };
  36738. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  36739. this._checkUniform(name);
  36740. this._matrices2x2[name] = value;
  36741. return this;
  36742. };
  36743. ShaderMaterial.prototype.setArray3 = function (name, value) {
  36744. this._checkUniform(name);
  36745. this._vectors3Arrays[name] = value;
  36746. return this;
  36747. };
  36748. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  36749. if (!mesh) {
  36750. return true;
  36751. }
  36752. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  36753. return false;
  36754. }
  36755. return false;
  36756. };
  36757. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  36758. var scene = this.getScene();
  36759. var engine = scene.getEngine();
  36760. if (!this.checkReadyOnEveryCall) {
  36761. if (this._renderId === scene.getRenderId()) {
  36762. if (this._checkCache(scene, mesh, useInstances)) {
  36763. return true;
  36764. }
  36765. }
  36766. }
  36767. // Instances
  36768. var defines = [];
  36769. var attribs = [];
  36770. var fallbacks = new BABYLON.EffectFallbacks();
  36771. if (useInstances) {
  36772. defines.push("#define INSTANCES");
  36773. }
  36774. for (var index = 0; index < this._options.defines.length; index++) {
  36775. defines.push(this._options.defines[index]);
  36776. }
  36777. for (var index = 0; index < this._options.attributes.length; index++) {
  36778. attribs.push(this._options.attributes[index]);
  36779. }
  36780. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36781. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36782. defines.push("#define VERTEXCOLOR");
  36783. }
  36784. // Bones
  36785. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  36786. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36787. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36788. if (mesh.numBoneInfluencers > 4) {
  36789. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36790. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36791. }
  36792. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36793. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36794. fallbacks.addCPUSkinningFallback(0, mesh);
  36795. if (this._options.uniforms.indexOf("mBones") === -1) {
  36796. this._options.uniforms.push("mBones");
  36797. }
  36798. }
  36799. else {
  36800. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36801. }
  36802. // Textures
  36803. for (var name in this._textures) {
  36804. if (!this._textures[name].isReady()) {
  36805. return false;
  36806. }
  36807. }
  36808. // Alpha test
  36809. if (engine.getAlphaTesting()) {
  36810. defines.push("#define ALPHATEST");
  36811. }
  36812. var previousEffect = this._effect;
  36813. var join = defines.join("\n");
  36814. this._effect = engine.createEffect(this._shaderPath, {
  36815. attributes: attribs,
  36816. uniformsNames: this._options.uniforms,
  36817. uniformBuffersNames: this._options.uniformBuffers,
  36818. samplers: this._options.samplers,
  36819. defines: join,
  36820. fallbacks: fallbacks,
  36821. onCompiled: this.onCompiled,
  36822. onError: this.onError
  36823. }, engine);
  36824. if (!this._effect.isReady()) {
  36825. return false;
  36826. }
  36827. if (previousEffect !== this._effect) {
  36828. scene.resetCachedMaterial();
  36829. }
  36830. this._renderId = scene.getRenderId();
  36831. return true;
  36832. };
  36833. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36834. var scene = this.getScene();
  36835. if (this._options.uniforms.indexOf("world") !== -1) {
  36836. this._effect.setMatrix("world", world);
  36837. }
  36838. if (this._options.uniforms.indexOf("worldView") !== -1) {
  36839. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  36840. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  36841. }
  36842. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  36843. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  36844. }
  36845. };
  36846. ShaderMaterial.prototype.bind = function (world, mesh) {
  36847. // Std values
  36848. this.bindOnlyWorldMatrix(world);
  36849. if (this.getScene().getCachedMaterial() !== this) {
  36850. if (this._options.uniforms.indexOf("view") !== -1) {
  36851. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  36852. }
  36853. if (this._options.uniforms.indexOf("projection") !== -1) {
  36854. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  36855. }
  36856. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  36857. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36858. }
  36859. // Bones
  36860. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  36861. var name;
  36862. // Texture
  36863. for (name in this._textures) {
  36864. this._effect.setTexture(name, this._textures[name]);
  36865. }
  36866. // Texture arrays
  36867. for (name in this._textureArrays) {
  36868. this._effect.setTextureArray(name, this._textureArrays[name]);
  36869. }
  36870. // Float
  36871. for (name in this._floats) {
  36872. this._effect.setFloat(name, this._floats[name]);
  36873. }
  36874. // Float s
  36875. for (name in this._floatsArrays) {
  36876. this._effect.setArray(name, this._floatsArrays[name]);
  36877. }
  36878. // Color3
  36879. for (name in this._colors3) {
  36880. this._effect.setColor3(name, this._colors3[name]);
  36881. }
  36882. // Color4
  36883. for (name in this._colors4) {
  36884. var color = this._colors4[name];
  36885. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  36886. }
  36887. // Vector2
  36888. for (name in this._vectors2) {
  36889. this._effect.setVector2(name, this._vectors2[name]);
  36890. }
  36891. // Vector3
  36892. for (name in this._vectors3) {
  36893. this._effect.setVector3(name, this._vectors3[name]);
  36894. }
  36895. // Vector4
  36896. for (name in this._vectors4) {
  36897. this._effect.setVector4(name, this._vectors4[name]);
  36898. }
  36899. // Matrix
  36900. for (name in this._matrices) {
  36901. this._effect.setMatrix(name, this._matrices[name]);
  36902. }
  36903. // Matrix 3x3
  36904. for (name in this._matrices3x3) {
  36905. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  36906. }
  36907. // Matrix 2x2
  36908. for (name in this._matrices2x2) {
  36909. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  36910. }
  36911. // Vector3Array
  36912. for (name in this._vectors3Arrays) {
  36913. this._effect.setArray3(name, this._vectors3Arrays[name]);
  36914. }
  36915. }
  36916. this._afterBind(mesh);
  36917. };
  36918. ShaderMaterial.prototype.getActiveTextures = function () {
  36919. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36920. for (var name in this._textures) {
  36921. activeTextures.push(this._textures[name]);
  36922. }
  36923. for (var name in this._textureArrays) {
  36924. var array = this._textureArrays[name];
  36925. for (var index = 0; index < array.length; index++) {
  36926. activeTextures.push(array[index]);
  36927. }
  36928. }
  36929. return activeTextures;
  36930. };
  36931. ShaderMaterial.prototype.clone = function (name) {
  36932. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  36933. return newShaderMaterial;
  36934. };
  36935. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36936. if (forceDisposeTextures) {
  36937. var name;
  36938. for (name in this._textures) {
  36939. this._textures[name].dispose();
  36940. }
  36941. for (name in this._textureArrays) {
  36942. var array = this._textureArrays[name];
  36943. for (var index = 0; index < array.length; index++) {
  36944. array[index].dispose();
  36945. }
  36946. }
  36947. }
  36948. this._textures = {};
  36949. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36950. };
  36951. ShaderMaterial.prototype.serialize = function () {
  36952. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36953. serializationObject.customType = "BABYLON.ShaderMaterial";
  36954. serializationObject.options = this._options;
  36955. serializationObject.shaderPath = this._shaderPath;
  36956. var name;
  36957. // Texture
  36958. serializationObject.textures = {};
  36959. for (name in this._textures) {
  36960. serializationObject.textures[name] = this._textures[name].serialize();
  36961. }
  36962. // Texture arrays
  36963. serializationObject.textureArrays = {};
  36964. for (name in this._textureArrays) {
  36965. serializationObject.textureArrays[name] = [];
  36966. var array = this._textureArrays[name];
  36967. for (var index = 0; index < array.length; index++) {
  36968. serializationObject.textureArrays[name].push(array[index].serialize());
  36969. }
  36970. }
  36971. // Float
  36972. serializationObject.floats = {};
  36973. for (name in this._floats) {
  36974. serializationObject.floats[name] = this._floats[name];
  36975. }
  36976. // Float s
  36977. serializationObject.floatArrays = {};
  36978. for (name in this._floatsArrays) {
  36979. serializationObject.floatArrays[name] = this._floatsArrays[name];
  36980. }
  36981. // Color3
  36982. serializationObject.colors3 = {};
  36983. for (name in this._colors3) {
  36984. serializationObject.colors3[name] = this._colors3[name].asArray();
  36985. }
  36986. // Color4
  36987. serializationObject.colors4 = {};
  36988. for (name in this._colors4) {
  36989. serializationObject.colors4[name] = this._colors4[name].asArray();
  36990. }
  36991. // Vector2
  36992. serializationObject.vectors2 = {};
  36993. for (name in this._vectors2) {
  36994. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  36995. }
  36996. // Vector3
  36997. serializationObject.vectors3 = {};
  36998. for (name in this._vectors3) {
  36999. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  37000. }
  37001. // Vector4
  37002. serializationObject.vectors4 = {};
  37003. for (name in this._vectors4) {
  37004. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  37005. }
  37006. // Matrix
  37007. serializationObject.matrices = {};
  37008. for (name in this._matrices) {
  37009. serializationObject.matrices[name] = this._matrices[name].asArray();
  37010. }
  37011. // Matrix 3x3
  37012. serializationObject.matrices3x3 = {};
  37013. for (name in this._matrices3x3) {
  37014. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  37015. }
  37016. // Matrix 2x2
  37017. serializationObject.matrices2x2 = {};
  37018. for (name in this._matrices2x2) {
  37019. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  37020. }
  37021. // Vector3Array
  37022. serializationObject.vectors3Arrays = {};
  37023. for (name in this._vectors3Arrays) {
  37024. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  37025. }
  37026. return serializationObject;
  37027. };
  37028. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  37029. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  37030. var name;
  37031. // Texture
  37032. for (name in source.textures) {
  37033. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  37034. }
  37035. // Texture arrays
  37036. for (name in source.textureArrays) {
  37037. var array = source.textureArrays[name];
  37038. var textureArray = new Array();
  37039. for (var index = 0; index < array.length; index++) {
  37040. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  37041. }
  37042. material.setTextureArray(name, textureArray);
  37043. }
  37044. // Float
  37045. for (name in source.floats) {
  37046. material.setFloat(name, source.floats[name]);
  37047. }
  37048. // Float s
  37049. for (name in source.floatsArrays) {
  37050. material.setFloats(name, source.floatsArrays[name]);
  37051. }
  37052. // Color3
  37053. for (name in source.colors3) {
  37054. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  37055. }
  37056. // Color4
  37057. for (name in source.colors4) {
  37058. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  37059. }
  37060. // Vector2
  37061. for (name in source.vectors2) {
  37062. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  37063. }
  37064. // Vector3
  37065. for (name in source.vectors3) {
  37066. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  37067. }
  37068. // Vector4
  37069. for (name in source.vectors4) {
  37070. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  37071. }
  37072. // Matrix
  37073. for (name in source.matrices) {
  37074. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  37075. }
  37076. // Matrix 3x3
  37077. for (name in source.matrices3x3) {
  37078. material.setMatrix3x3(name, source.matrices3x3[name]);
  37079. }
  37080. // Matrix 2x2
  37081. for (name in source.matrices2x2) {
  37082. material.setMatrix2x2(name, source.matrices2x2[name]);
  37083. }
  37084. // Vector3Array
  37085. for (name in source.vectors3Arrays) {
  37086. material.setArray3(name, source.vectors3Arrays[name]);
  37087. }
  37088. return material;
  37089. };
  37090. return ShaderMaterial;
  37091. }(BABYLON.Material));
  37092. BABYLON.ShaderMaterial = ShaderMaterial;
  37093. })(BABYLON || (BABYLON = {}));
  37094. //# sourceMappingURL=babylon.shaderMaterial.js.map
  37095. var BABYLON;
  37096. (function (BABYLON) {
  37097. var MeshBuilder = (function () {
  37098. function MeshBuilder() {
  37099. }
  37100. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  37101. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  37102. return BABYLON.Mesh.DOUBLESIDE;
  37103. }
  37104. if (orientation === undefined || orientation === null) {
  37105. return BABYLON.Mesh.FRONTSIDE;
  37106. }
  37107. return orientation;
  37108. };
  37109. /**
  37110. * Creates a box mesh.
  37111. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  37112. * The parameter `size` sets the size (float) of each box side (default 1).
  37113. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  37114. * 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).
  37115. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37116. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37117. * 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).
  37118. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37120. */
  37121. MeshBuilder.CreateBox = function (name, options, scene) {
  37122. var box = new BABYLON.Mesh(name, scene);
  37123. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37124. box.sideOrientation = options.sideOrientation;
  37125. var vertexData = BABYLON.VertexData.CreateBox(options);
  37126. vertexData.applyToMesh(box, options.updatable);
  37127. return box;
  37128. };
  37129. /**
  37130. * Creates a sphere mesh.
  37131. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  37132. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  37133. * 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`).
  37134. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  37135. * 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
  37136. * 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).
  37137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37138. * 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).
  37139. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37141. */
  37142. MeshBuilder.CreateSphere = function (name, options, scene) {
  37143. var sphere = new BABYLON.Mesh(name, scene);
  37144. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37145. sphere.sideOrientation = options.sideOrientation;
  37146. var vertexData = BABYLON.VertexData.CreateSphere(options);
  37147. vertexData.applyToMesh(sphere, options.updatable);
  37148. return sphere;
  37149. };
  37150. /**
  37151. * Creates a plane polygonal mesh. By default, this is a disc.
  37152. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  37153. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  37154. * 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.
  37155. * 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
  37156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37157. * 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).
  37158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37160. */
  37161. MeshBuilder.CreateDisc = function (name, options, scene) {
  37162. var disc = new BABYLON.Mesh(name, scene);
  37163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37164. disc.sideOrientation = options.sideOrientation;
  37165. var vertexData = BABYLON.VertexData.CreateDisc(options);
  37166. vertexData.applyToMesh(disc, options.updatable);
  37167. return disc;
  37168. };
  37169. /**
  37170. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  37171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  37172. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  37173. * 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`).
  37174. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  37175. * 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.
  37176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37177. * 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).
  37178. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37180. */
  37181. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  37182. var sphere = new BABYLON.Mesh(name, scene);
  37183. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37184. sphere.sideOrientation = options.sideOrientation;
  37185. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  37186. vertexData.applyToMesh(sphere, options.updatable);
  37187. return sphere;
  37188. };
  37189. ;
  37190. /**
  37191. * Creates a ribbon mesh.
  37192. * 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.
  37193. *
  37194. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  37195. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  37196. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  37197. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  37198. * 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.
  37199. * 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.
  37200. * 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
  37201. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37202. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37204. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37205. * The 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.
  37206. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  37207. * 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
  37208. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  37209. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  37210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37211. */
  37212. MeshBuilder.CreateRibbon = function (name, options, scene) {
  37213. var pathArray = options.pathArray;
  37214. var closeArray = options.closeArray;
  37215. var closePath = options.closePath;
  37216. var offset = options.offset;
  37217. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37218. var instance = options.instance;
  37219. var updatable = options.updatable;
  37220. if (instance) {
  37221. // positionFunction : ribbon case
  37222. // only pathArray and sideOrientation parameters are taken into account for positions update
  37223. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  37224. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  37225. var positionFunction = function (positions) {
  37226. var minlg = pathArray[0].length;
  37227. var i = 0;
  37228. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  37229. for (var si = 1; si <= ns; si++) {
  37230. for (var p = 0; p < pathArray.length; p++) {
  37231. var path = pathArray[p];
  37232. var l = path.length;
  37233. minlg = (minlg < l) ? minlg : l;
  37234. var j = 0;
  37235. while (j < minlg) {
  37236. positions[i] = path[j].x;
  37237. positions[i + 1] = path[j].y;
  37238. positions[i + 2] = path[j].z;
  37239. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  37240. BABYLON.Tmp.Vector3[0].x = path[j].x;
  37241. }
  37242. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  37243. BABYLON.Tmp.Vector3[1].x = path[j].x;
  37244. }
  37245. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  37246. BABYLON.Tmp.Vector3[0].y = path[j].y;
  37247. }
  37248. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  37249. BABYLON.Tmp.Vector3[1].y = path[j].y;
  37250. }
  37251. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  37252. BABYLON.Tmp.Vector3[0].z = path[j].z;
  37253. }
  37254. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  37255. BABYLON.Tmp.Vector3[1].z = path[j].z;
  37256. }
  37257. j++;
  37258. i += 3;
  37259. }
  37260. if (instance._closePath) {
  37261. positions[i] = path[0].x;
  37262. positions[i + 1] = path[0].y;
  37263. positions[i + 2] = path[0].z;
  37264. i += 3;
  37265. }
  37266. }
  37267. }
  37268. };
  37269. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37270. positionFunction(positions);
  37271. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  37272. instance._boundingInfo.update(instance._worldMatrix);
  37273. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  37274. if (options.colors) {
  37275. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37276. for (var c = 0; c < options.colors.length; c++) {
  37277. colors[c * 4] = options.colors[c].r;
  37278. colors[c * 4 + 1] = options.colors[c].g;
  37279. colors[c * 4 + 2] = options.colors[c].b;
  37280. colors[c * 4 + 3] = options.colors[c].a;
  37281. }
  37282. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  37283. }
  37284. if (options.uvs) {
  37285. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37286. for (var i = 0; i < options.uvs.length; i++) {
  37287. uvs[i * 2] = options.uvs[i].x;
  37288. uvs[i * 2 + 1] = options.uvs[i].y;
  37289. }
  37290. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  37291. }
  37292. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  37293. var indices = instance.getIndices();
  37294. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37295. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  37296. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  37297. if (instance._closePath) {
  37298. var indexFirst = 0;
  37299. var indexLast = 0;
  37300. for (var p = 0; p < pathArray.length; p++) {
  37301. indexFirst = instance._idx[p] * 3;
  37302. if (p + 1 < pathArray.length) {
  37303. indexLast = (instance._idx[p + 1] - 1) * 3;
  37304. }
  37305. else {
  37306. indexLast = normals.length - 3;
  37307. }
  37308. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37309. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37310. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37311. normals[indexLast] = normals[indexFirst];
  37312. normals[indexLast + 1] = normals[indexFirst + 1];
  37313. normals[indexLast + 2] = normals[indexFirst + 2];
  37314. }
  37315. }
  37316. if (!(instance.areNormalsFrozen)) {
  37317. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  37318. }
  37319. }
  37320. return instance;
  37321. }
  37322. else {
  37323. var ribbon = new BABYLON.Mesh(name, scene);
  37324. ribbon.sideOrientation = sideOrientation;
  37325. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  37326. if (closePath) {
  37327. ribbon._idx = vertexData._idx;
  37328. }
  37329. ribbon._closePath = closePath;
  37330. ribbon._closeArray = closeArray;
  37331. vertexData.applyToMesh(ribbon, updatable);
  37332. return ribbon;
  37333. }
  37334. };
  37335. /**
  37336. * Creates a cylinder or a cone mesh.
  37337. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  37338. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  37339. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  37340. * 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.
  37341. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  37342. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  37343. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  37344. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  37345. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  37346. * 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).
  37347. * 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
  37348. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  37349. * 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
  37350. * 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.
  37351. * If `enclose` is false, a ring surface is one element.
  37352. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  37353. * 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
  37354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37355. * 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).
  37356. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37358. */
  37359. MeshBuilder.CreateCylinder = function (name, options, scene) {
  37360. var cylinder = new BABYLON.Mesh(name, scene);
  37361. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37362. cylinder.sideOrientation = options.sideOrientation;
  37363. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  37364. vertexData.applyToMesh(cylinder, options.updatable);
  37365. return cylinder;
  37366. };
  37367. /**
  37368. * Creates a torus mesh.
  37369. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  37370. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  37371. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  37372. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  37373. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37374. * 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).
  37375. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37377. */
  37378. MeshBuilder.CreateTorus = function (name, options, scene) {
  37379. var torus = new BABYLON.Mesh(name, scene);
  37380. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37381. torus.sideOrientation = options.sideOrientation;
  37382. var vertexData = BABYLON.VertexData.CreateTorus(options);
  37383. vertexData.applyToMesh(torus, options.updatable);
  37384. return torus;
  37385. };
  37386. /**
  37387. * Creates a torus knot mesh.
  37388. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  37389. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  37390. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  37391. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  37392. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  37393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37394. * 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).
  37395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37397. */
  37398. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  37399. var torusKnot = new BABYLON.Mesh(name, scene);
  37400. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37401. torusKnot.sideOrientation = options.sideOrientation;
  37402. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  37403. vertexData.applyToMesh(torusKnot, options.updatable);
  37404. return torusKnot;
  37405. };
  37406. /**
  37407. * Creates a line system mesh.
  37408. * A line system is a pool of many lines gathered in a single mesh.
  37409. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  37410. * 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.
  37411. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  37412. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  37413. * 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
  37414. * 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
  37415. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  37416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37417. */
  37418. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  37419. var instance = options.instance;
  37420. var lines = options.lines;
  37421. if (instance) {
  37422. var positionFunction = function (positions) {
  37423. var i = 0;
  37424. for (var l = 0; l < lines.length; l++) {
  37425. var points = lines[l];
  37426. for (var p = 0; p < points.length; p++) {
  37427. positions[i] = points[p].x;
  37428. positions[i + 1] = points[p].y;
  37429. positions[i + 2] = points[p].z;
  37430. i += 3;
  37431. }
  37432. }
  37433. };
  37434. instance.updateMeshPositions(positionFunction, false);
  37435. return instance;
  37436. }
  37437. // line system creation
  37438. var lineSystem = new BABYLON.LinesMesh(name, scene);
  37439. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  37440. vertexData.applyToMesh(lineSystem, options.updatable);
  37441. return lineSystem;
  37442. };
  37443. /**
  37444. * Creates a line mesh.
  37445. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  37446. * 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.
  37447. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37448. * The parameter `points` is an array successive Vector3.
  37449. * 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
  37450. * When updating an instance, remember that only point positions can change, not the number of points.
  37451. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37452. */
  37453. MeshBuilder.CreateLines = function (name, options, scene) {
  37454. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  37455. return lines;
  37456. };
  37457. /**
  37458. * Creates a dashed line mesh.
  37459. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  37460. * 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.
  37461. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37462. * The parameter `points` is an array successive Vector3.
  37463. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  37464. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  37465. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  37466. * 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
  37467. * When updating an instance, remember that only point positions can change, not the number of points.
  37468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37469. */
  37470. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  37471. var points = options.points;
  37472. var instance = options.instance;
  37473. var gapSize = options.gapSize;
  37474. var dashNb = options.dashNb;
  37475. var dashSize = options.dashSize;
  37476. if (instance) {
  37477. var positionFunction = function (positions) {
  37478. var curvect = BABYLON.Vector3.Zero();
  37479. var nbSeg = positions.length / 6;
  37480. var lg = 0;
  37481. var nb = 0;
  37482. var shft = 0;
  37483. var dashshft = 0;
  37484. var curshft = 0;
  37485. var p = 0;
  37486. var i = 0;
  37487. var j = 0;
  37488. for (i = 0; i < points.length - 1; i++) {
  37489. points[i + 1].subtractToRef(points[i], curvect);
  37490. lg += curvect.length();
  37491. }
  37492. shft = lg / nbSeg;
  37493. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  37494. for (i = 0; i < points.length - 1; i++) {
  37495. points[i + 1].subtractToRef(points[i], curvect);
  37496. nb = Math.floor(curvect.length() / shft);
  37497. curvect.normalize();
  37498. j = 0;
  37499. while (j < nb && p < positions.length) {
  37500. curshft = shft * j;
  37501. positions[p] = points[i].x + curshft * curvect.x;
  37502. positions[p + 1] = points[i].y + curshft * curvect.y;
  37503. positions[p + 2] = points[i].z + curshft * curvect.z;
  37504. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  37505. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  37506. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  37507. p += 6;
  37508. j++;
  37509. }
  37510. }
  37511. while (p < positions.length) {
  37512. positions[p] = points[i].x;
  37513. positions[p + 1] = points[i].y;
  37514. positions[p + 2] = points[i].z;
  37515. p += 3;
  37516. }
  37517. };
  37518. instance.updateMeshPositions(positionFunction, false);
  37519. return instance;
  37520. }
  37521. // dashed lines creation
  37522. var dashedLines = new BABYLON.LinesMesh(name, scene);
  37523. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  37524. vertexData.applyToMesh(dashedLines, options.updatable);
  37525. dashedLines.dashSize = dashSize;
  37526. dashedLines.gapSize = gapSize;
  37527. return dashedLines;
  37528. };
  37529. /**
  37530. * Creates an extruded shape mesh.
  37531. * 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.
  37532. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  37533. *
  37534. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37535. * 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
  37536. * extruded along the Z axis.
  37537. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37538. * 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.
  37539. * The parameter `scale` (float, default 1) is the value to scale the shape.
  37540. * 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
  37541. * 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
  37542. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37543. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37544. * 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).
  37545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37546. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37548. */
  37549. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  37550. var path = options.path;
  37551. var shape = options.shape;
  37552. var scale = options.scale || 1;
  37553. var rotation = options.rotation || 0;
  37554. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37555. var updatable = options.updatable;
  37556. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37557. var instance = options.instance;
  37558. var invertUV = options.invertUV || false;
  37559. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37560. };
  37561. /**
  37562. * Creates an custom extruded shape mesh.
  37563. * 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.
  37564. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  37565. *
  37566. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37567. * 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
  37568. * extruded along the Z axis.
  37569. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37570. * 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
  37571. * and the distance of this point from the begining of the path :
  37572. * ```javascript
  37573. * var rotationFunction = function(i, distance) {
  37574. * // do things
  37575. * return rotationValue; }
  37576. * ```
  37577. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  37578. * 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
  37579. * and the distance of this point from the begining of the path :
  37580. * ```javascript
  37581. * var scaleFunction = function(i, distance) {
  37582. * // do things
  37583. * return scaleValue;}
  37584. * ```
  37585. * It must returns a float value that will be the scale value applied to the shape on each path point.
  37586. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  37587. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  37588. * 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
  37589. * 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
  37590. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37592. * 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).
  37593. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37594. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37596. */
  37597. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  37598. var path = options.path;
  37599. var shape = options.shape;
  37600. var scaleFunction = options.scaleFunction || (function () { return 1; });
  37601. var rotationFunction = options.rotationFunction || (function () { return 0; });
  37602. var ribbonCloseArray = options.ribbonCloseArray || false;
  37603. var ribbonClosePath = options.ribbonClosePath || false;
  37604. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37605. var updatable = options.updatable;
  37606. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37607. var instance = options.instance;
  37608. var invertUV = options.invertUV || false;
  37609. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37610. };
  37611. /**
  37612. * Creates lathe mesh.
  37613. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  37614. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  37615. *
  37616. * 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
  37617. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  37618. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  37619. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  37620. * 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.
  37621. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  37622. * 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
  37623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37624. * 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).
  37625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37626. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37628. */
  37629. MeshBuilder.CreateLathe = function (name, options, scene) {
  37630. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  37631. var closed = (options.closed === undefined) ? true : options.closed;
  37632. var shape = options.shape;
  37633. var radius = options.radius || 1;
  37634. var tessellation = options.tessellation || 64;
  37635. var updatable = options.updatable;
  37636. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37637. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37638. var pi2 = Math.PI * 2;
  37639. var paths = new Array();
  37640. var invertUV = options.invertUV || false;
  37641. var i = 0;
  37642. var p = 0;
  37643. var step = pi2 / tessellation * arc;
  37644. var rotated;
  37645. var path = new Array();
  37646. ;
  37647. for (i = 0; i <= tessellation; i++) {
  37648. var path = [];
  37649. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  37650. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  37651. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  37652. }
  37653. for (p = 0; p < shape.length; p++) {
  37654. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  37655. path.push(rotated);
  37656. }
  37657. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  37658. 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));
  37659. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  37660. }
  37661. paths.push(path);
  37662. }
  37663. // lathe ribbon
  37664. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37665. return lathe;
  37666. };
  37667. /**
  37668. * Creates a plane mesh.
  37669. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37670. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  37671. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  37672. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  37673. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37674. * 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).
  37675. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37677. */
  37678. MeshBuilder.CreatePlane = function (name, options, scene) {
  37679. var plane = new BABYLON.Mesh(name, scene);
  37680. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37681. plane.sideOrientation = options.sideOrientation;
  37682. var vertexData = BABYLON.VertexData.CreatePlane(options);
  37683. vertexData.applyToMesh(plane, options.updatable);
  37684. if (options.sourcePlane) {
  37685. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  37686. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  37687. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  37688. plane.rotate(vectorProduct, product);
  37689. }
  37690. return plane;
  37691. };
  37692. /**
  37693. * Creates a ground mesh.
  37694. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37695. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  37696. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  37697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37698. */
  37699. MeshBuilder.CreateGround = function (name, options, scene) {
  37700. var ground = new BABYLON.GroundMesh(name, scene);
  37701. ground._setReady(false);
  37702. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37703. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37704. ground._width = options.width || 1;
  37705. ground._height = options.height || 1;
  37706. ground._maxX = ground._width / 2;
  37707. ground._maxZ = ground._height / 2;
  37708. ground._minX = -ground._maxX;
  37709. ground._minZ = -ground._maxZ;
  37710. var vertexData = BABYLON.VertexData.CreateGround(options);
  37711. vertexData.applyToMesh(ground, options.updatable);
  37712. ground._setReady(true);
  37713. return ground;
  37714. };
  37715. /**
  37716. * Creates a tiled ground mesh.
  37717. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  37718. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  37719. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  37720. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  37721. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  37722. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  37723. * numbers of subdivisions on the ground width and height of each tile.
  37724. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37725. */
  37726. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  37727. var tiledGround = new BABYLON.Mesh(name, scene);
  37728. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  37729. vertexData.applyToMesh(tiledGround, options.updatable);
  37730. return tiledGround;
  37731. };
  37732. /**
  37733. * Creates a ground mesh from a height map.
  37734. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  37735. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  37736. * The parameter `url` sets the URL of the height map image resource.
  37737. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  37738. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  37739. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  37740. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  37741. * 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.
  37742. * 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).
  37743. * This function is passed the newly built mesh :
  37744. * ```javascript
  37745. * function(mesh) { // do things
  37746. * return; }
  37747. * ```
  37748. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37749. */
  37750. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  37751. var width = options.width || 10.0;
  37752. var height = options.height || 10.0;
  37753. var subdivisions = options.subdivisions || 1 | 0;
  37754. var minHeight = options.minHeight || 0.0;
  37755. var maxHeight = options.maxHeight || 10.0;
  37756. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37757. var updatable = options.updatable;
  37758. var onReady = options.onReady;
  37759. var ground = new BABYLON.GroundMesh(name, scene);
  37760. ground._subdivisionsX = subdivisions;
  37761. ground._subdivisionsY = subdivisions;
  37762. ground._width = width;
  37763. ground._height = height;
  37764. ground._maxX = ground._width / 2.0;
  37765. ground._maxZ = ground._height / 2.0;
  37766. ground._minX = -ground._maxX;
  37767. ground._minZ = -ground._maxZ;
  37768. ground._setReady(false);
  37769. var onload = function (img) {
  37770. // Getting height map data
  37771. var canvas = document.createElement("canvas");
  37772. var context = canvas.getContext("2d");
  37773. var bufferWidth = img.width;
  37774. var bufferHeight = img.height;
  37775. canvas.width = bufferWidth;
  37776. canvas.height = bufferHeight;
  37777. context.drawImage(img, 0, 0);
  37778. // Create VertexData from map data
  37779. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  37780. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  37781. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  37782. width: width, height: height,
  37783. subdivisions: subdivisions,
  37784. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  37785. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  37786. });
  37787. vertexData.applyToMesh(ground, updatable);
  37788. ground._setReady(true);
  37789. //execute ready callback, if set
  37790. if (onReady) {
  37791. onReady(ground);
  37792. }
  37793. };
  37794. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  37795. return ground;
  37796. };
  37797. /**
  37798. * Creates a polygon mesh.
  37799. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  37800. * 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.
  37801. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37803. * 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).
  37804. * Remember you can only change the shape positions, not their number when updating a polygon.
  37805. */
  37806. MeshBuilder.CreatePolygon = function (name, options, scene) {
  37807. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37808. var shape = options.shape;
  37809. var holes = options.holes || [];
  37810. var depth = options.depth || 0;
  37811. var contours = [];
  37812. var hole = [];
  37813. for (var i = 0; i < shape.length; i++) {
  37814. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  37815. }
  37816. var epsilon = 0.00000001;
  37817. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  37818. contours.pop();
  37819. }
  37820. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  37821. for (var hNb = 0; hNb < holes.length; hNb++) {
  37822. hole = [];
  37823. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  37824. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  37825. }
  37826. polygonTriangulation.addHole(hole);
  37827. }
  37828. var polygon = polygonTriangulation.build(options.updatable, depth);
  37829. polygon.sideOrientation = options.sideOrientation;
  37830. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  37831. vertexData.applyToMesh(polygon, options.updatable);
  37832. return polygon;
  37833. };
  37834. ;
  37835. /**
  37836. * Creates an extruded polygon mesh, with depth in the Y direction.
  37837. * 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).
  37838. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37839. */
  37840. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  37841. return MeshBuilder.CreatePolygon(name, options, scene);
  37842. };
  37843. ;
  37844. /**
  37845. * Creates a tube mesh.
  37846. * 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.
  37847. *
  37848. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  37849. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  37850. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  37851. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  37852. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  37853. * 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.
  37854. * It must return a radius value (positive float) :
  37855. * ```javascript
  37856. * var radiusFunction = function(i, distance) {
  37857. * // do things
  37858. * return radius; }
  37859. * ```
  37860. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  37861. * 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
  37862. * 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
  37863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37864. * 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).
  37865. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37866. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37868. */
  37869. MeshBuilder.CreateTube = function (name, options, scene) {
  37870. var path = options.path;
  37871. var radius = options.radius || 1.0;
  37872. var tessellation = options.tessellation || 64 | 0;
  37873. var radiusFunction = options.radiusFunction;
  37874. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37875. var invertUV = options.invertUV || false;
  37876. var updatable = options.updatable;
  37877. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37878. var instance = options.instance;
  37879. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  37880. // tube geometry
  37881. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  37882. var tangents = path3D.getTangents();
  37883. var normals = path3D.getNormals();
  37884. var distances = path3D.getDistances();
  37885. var pi2 = Math.PI * 2;
  37886. var step = pi2 / tessellation * arc;
  37887. var returnRadius = function () { return radius; };
  37888. var radiusFunctionFinal = radiusFunction || returnRadius;
  37889. var circlePath;
  37890. var rad;
  37891. var normal;
  37892. var rotated;
  37893. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  37894. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  37895. for (var i = 0; i < path.length; i++) {
  37896. rad = radiusFunctionFinal(i, distances[i]); // current radius
  37897. circlePath = Array(); // current circle array
  37898. normal = normals[i]; // current normal
  37899. for (var t = 0; t < tessellation; t++) {
  37900. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  37901. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  37902. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  37903. rotated.scaleInPlace(rad).addInPlace(path[i]);
  37904. circlePath[t] = rotated;
  37905. }
  37906. circlePaths[index] = circlePath;
  37907. index++;
  37908. }
  37909. // cap
  37910. var capPath = function (nbPoints, pathIndex) {
  37911. var pointCap = Array();
  37912. for (var i = 0; i < nbPoints; i++) {
  37913. pointCap.push(path[pathIndex]);
  37914. }
  37915. return pointCap;
  37916. };
  37917. switch (cap) {
  37918. case BABYLON.Mesh.NO_CAP:
  37919. break;
  37920. case BABYLON.Mesh.CAP_START:
  37921. circlePaths[0] = capPath(tessellation, 0);
  37922. circlePaths[1] = circlePaths[2].slice(0);
  37923. break;
  37924. case BABYLON.Mesh.CAP_END:
  37925. circlePaths[index] = circlePaths[index - 1].slice(0);
  37926. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37927. break;
  37928. case BABYLON.Mesh.CAP_ALL:
  37929. circlePaths[0] = capPath(tessellation, 0);
  37930. circlePaths[1] = circlePaths[2].slice(0);
  37931. circlePaths[index] = circlePaths[index - 1].slice(0);
  37932. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37933. break;
  37934. default:
  37935. break;
  37936. }
  37937. return circlePaths;
  37938. };
  37939. var path3D;
  37940. var pathArray;
  37941. if (instance) {
  37942. var arc = options.arc || instance.arc;
  37943. path3D = (instance.path3D).update(path);
  37944. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  37945. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  37946. instance.path3D = path3D;
  37947. instance.pathArray = pathArray;
  37948. instance.arc = arc;
  37949. return instance;
  37950. }
  37951. // tube creation
  37952. path3D = new BABYLON.Path3D(path);
  37953. var newPathArray = new Array();
  37954. cap = (cap < 0 || cap > 3) ? 0 : cap;
  37955. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  37956. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37957. tube.pathArray = pathArray;
  37958. tube.path3D = path3D;
  37959. tube.tessellation = tessellation;
  37960. tube.cap = cap;
  37961. tube.arc = options.arc;
  37962. return tube;
  37963. };
  37964. /**
  37965. * Creates a polyhedron mesh.
  37966. *
  37967. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  37968. * 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
  37969. * to choose the wanted type.
  37970. * The parameter `size` (positive float, default 1) sets the polygon size.
  37971. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  37972. * 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`.
  37973. * 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
  37974. * 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)`).
  37975. * 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
  37976. * 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.
  37977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37978. * 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).
  37979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37981. */
  37982. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  37983. var polyhedron = new BABYLON.Mesh(name, scene);
  37984. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37985. polyhedron.sideOrientation = options.sideOrientation;
  37986. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  37987. vertexData.applyToMesh(polyhedron, options.updatable);
  37988. return polyhedron;
  37989. };
  37990. /**
  37991. * Creates a decal mesh.
  37992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  37993. * 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.
  37994. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  37995. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  37996. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  37997. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  37998. */
  37999. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  38000. var indices = sourceMesh.getIndices();
  38001. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38002. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38003. var position = options.position || BABYLON.Vector3.Zero();
  38004. var normal = options.normal || BABYLON.Vector3.Up();
  38005. var size = options.size || BABYLON.Vector3.One();
  38006. var angle = options.angle || 0;
  38007. // Getting correct rotation
  38008. if (!normal) {
  38009. var target = new BABYLON.Vector3(0, 0, 1);
  38010. var camera = sourceMesh.getScene().activeCamera;
  38011. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  38012. normal = camera.globalPosition.subtract(cameraWorldTarget);
  38013. }
  38014. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  38015. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  38016. var pitch = Math.atan2(normal.y, len);
  38017. // Matrix
  38018. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  38019. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  38020. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  38021. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  38022. var vertexData = new BABYLON.VertexData();
  38023. vertexData.indices = [];
  38024. vertexData.positions = [];
  38025. vertexData.normals = [];
  38026. vertexData.uvs = [];
  38027. var currentVertexDataIndex = 0;
  38028. var extractDecalVector3 = function (indexId) {
  38029. var vertexId = indices[indexId];
  38030. var result = new BABYLON.PositionNormalVertex();
  38031. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  38032. // Send vector to decal local world
  38033. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  38034. // Get normal
  38035. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  38036. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  38037. return result;
  38038. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  38039. var clip = function (vertices, axis) {
  38040. if (vertices.length === 0) {
  38041. return vertices;
  38042. }
  38043. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  38044. var clipVertices = function (v0, v1) {
  38045. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  38046. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  38047. };
  38048. var result = new Array();
  38049. for (var index = 0; index < vertices.length; index += 3) {
  38050. var v1Out;
  38051. var v2Out;
  38052. var v3Out;
  38053. var total = 0;
  38054. var nV1, nV2, nV3, nV4;
  38055. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  38056. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  38057. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  38058. v1Out = d1 > 0;
  38059. v2Out = d2 > 0;
  38060. v3Out = d3 > 0;
  38061. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  38062. switch (total) {
  38063. case 0:
  38064. result.push(vertices[index]);
  38065. result.push(vertices[index + 1]);
  38066. result.push(vertices[index + 2]);
  38067. break;
  38068. case 1:
  38069. if (v1Out) {
  38070. nV1 = vertices[index + 1];
  38071. nV2 = vertices[index + 2];
  38072. nV3 = clipVertices(vertices[index], nV1);
  38073. nV4 = clipVertices(vertices[index], nV2);
  38074. }
  38075. if (v2Out) {
  38076. nV1 = vertices[index];
  38077. nV2 = vertices[index + 2];
  38078. nV3 = clipVertices(vertices[index + 1], nV1);
  38079. nV4 = clipVertices(vertices[index + 1], nV2);
  38080. result.push(nV3);
  38081. result.push(nV2.clone());
  38082. result.push(nV1.clone());
  38083. result.push(nV2.clone());
  38084. result.push(nV3.clone());
  38085. result.push(nV4);
  38086. break;
  38087. }
  38088. if (v3Out) {
  38089. nV1 = vertices[index];
  38090. nV2 = vertices[index + 1];
  38091. nV3 = clipVertices(vertices[index + 2], nV1);
  38092. nV4 = clipVertices(vertices[index + 2], nV2);
  38093. }
  38094. result.push(nV1.clone());
  38095. result.push(nV2.clone());
  38096. result.push(nV3);
  38097. result.push(nV4);
  38098. result.push(nV3.clone());
  38099. result.push(nV2.clone());
  38100. break;
  38101. case 2:
  38102. if (!v1Out) {
  38103. nV1 = vertices[index].clone();
  38104. nV2 = clipVertices(nV1, vertices[index + 1]);
  38105. nV3 = clipVertices(nV1, vertices[index + 2]);
  38106. result.push(nV1);
  38107. result.push(nV2);
  38108. result.push(nV3);
  38109. }
  38110. if (!v2Out) {
  38111. nV1 = vertices[index + 1].clone();
  38112. nV2 = clipVertices(nV1, vertices[index + 2]);
  38113. nV3 = clipVertices(nV1, vertices[index]);
  38114. result.push(nV1);
  38115. result.push(nV2);
  38116. result.push(nV3);
  38117. }
  38118. if (!v3Out) {
  38119. nV1 = vertices[index + 2].clone();
  38120. nV2 = clipVertices(nV1, vertices[index]);
  38121. nV3 = clipVertices(nV1, vertices[index + 1]);
  38122. result.push(nV1);
  38123. result.push(nV2);
  38124. result.push(nV3);
  38125. }
  38126. break;
  38127. case 3:
  38128. break;
  38129. }
  38130. }
  38131. return result;
  38132. };
  38133. for (var index = 0; index < indices.length; index += 3) {
  38134. var faceVertices = new Array();
  38135. faceVertices.push(extractDecalVector3(index));
  38136. faceVertices.push(extractDecalVector3(index + 1));
  38137. faceVertices.push(extractDecalVector3(index + 2));
  38138. // Clip
  38139. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  38140. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  38141. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  38142. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  38143. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  38144. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  38145. if (faceVertices.length === 0) {
  38146. continue;
  38147. }
  38148. // Add UVs and get back to world
  38149. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  38150. var vertex = faceVertices[vIndex];
  38151. //TODO check for Int32Array | Uint32Array | Uint16Array
  38152. vertexData.indices.push(currentVertexDataIndex);
  38153. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  38154. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  38155. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  38156. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  38157. currentVertexDataIndex++;
  38158. }
  38159. }
  38160. // Return mesh
  38161. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  38162. vertexData.applyToMesh(decal);
  38163. decal.position = position.clone();
  38164. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  38165. return decal;
  38166. };
  38167. // Privates
  38168. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  38169. // extrusion geometry
  38170. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  38171. var tangents = path3D.getTangents();
  38172. var normals = path3D.getNormals();
  38173. var binormals = path3D.getBinormals();
  38174. var distances = path3D.getDistances();
  38175. var angle = 0;
  38176. var returnScale = function () { return scale; };
  38177. var returnRotation = function () { return rotation; };
  38178. var rotate = custom ? rotateFunction : returnRotation;
  38179. var scl = custom ? scaleFunction : returnScale;
  38180. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38181. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38182. for (var i = 0; i < curve.length; i++) {
  38183. var shapePath = new Array();
  38184. var angleStep = rotate(i, distances[i]);
  38185. var scaleRatio = scl(i, distances[i]);
  38186. for (var p = 0; p < shape.length; p++) {
  38187. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  38188. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  38189. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  38190. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  38191. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  38192. shapePath[p] = rotated;
  38193. }
  38194. shapePaths[index] = shapePath;
  38195. angle += angleStep;
  38196. index++;
  38197. }
  38198. // cap
  38199. var capPath = function (shapePath) {
  38200. var pointCap = Array();
  38201. var barycenter = BABYLON.Vector3.Zero();
  38202. var i;
  38203. for (i = 0; i < shapePath.length; i++) {
  38204. barycenter.addInPlace(shapePath[i]);
  38205. }
  38206. barycenter.scaleInPlace(1.0 / shapePath.length);
  38207. for (i = 0; i < shapePath.length; i++) {
  38208. pointCap.push(barycenter);
  38209. }
  38210. return pointCap;
  38211. };
  38212. switch (cap) {
  38213. case BABYLON.Mesh.NO_CAP:
  38214. break;
  38215. case BABYLON.Mesh.CAP_START:
  38216. shapePaths[0] = capPath(shapePaths[2]);
  38217. shapePaths[1] = shapePaths[2];
  38218. break;
  38219. case BABYLON.Mesh.CAP_END:
  38220. shapePaths[index] = shapePaths[index - 1];
  38221. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38222. break;
  38223. case BABYLON.Mesh.CAP_ALL:
  38224. shapePaths[0] = capPath(shapePaths[2]);
  38225. shapePaths[1] = shapePaths[2];
  38226. shapePaths[index] = shapePaths[index - 1];
  38227. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38228. break;
  38229. default:
  38230. break;
  38231. }
  38232. return shapePaths;
  38233. };
  38234. var path3D;
  38235. var pathArray;
  38236. if (instance) {
  38237. path3D = (instance.path3D).update(curve);
  38238. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  38239. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  38240. return instance;
  38241. }
  38242. // extruded shape creation
  38243. path3D = new BABYLON.Path3D(curve);
  38244. var newShapePaths = new Array();
  38245. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38246. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  38247. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  38248. extrudedGeneric.pathArray = pathArray;
  38249. extrudedGeneric.path3D = path3D;
  38250. extrudedGeneric.cap = cap;
  38251. return extrudedGeneric;
  38252. };
  38253. return MeshBuilder;
  38254. }());
  38255. BABYLON.MeshBuilder = MeshBuilder;
  38256. })(BABYLON || (BABYLON = {}));
  38257. //# sourceMappingURL=babylon.meshBuilder.js.map
  38258. var BABYLON;
  38259. (function (BABYLON) {
  38260. var Layer = (function () {
  38261. function Layer(name, imgUrl, scene, isBackground, color) {
  38262. this.name = name;
  38263. this.scale = new BABYLON.Vector2(1, 1);
  38264. this.offset = new BABYLON.Vector2(0, 0);
  38265. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  38266. this.layerMask = 0x0FFFFFFF;
  38267. this._vertexBuffers = {};
  38268. // Events
  38269. /**
  38270. * An event triggered when the layer is disposed.
  38271. * @type {BABYLON.Observable}
  38272. */
  38273. this.onDisposeObservable = new BABYLON.Observable();
  38274. /**
  38275. * An event triggered before rendering the scene
  38276. * @type {BABYLON.Observable}
  38277. */
  38278. this.onBeforeRenderObservable = new BABYLON.Observable();
  38279. /**
  38280. * An event triggered after rendering the scene
  38281. * @type {BABYLON.Observable}
  38282. */
  38283. this.onAfterRenderObservable = new BABYLON.Observable();
  38284. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  38285. this.isBackground = isBackground === undefined ? true : isBackground;
  38286. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  38287. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38288. this._scene.layers.push(this);
  38289. var engine = this._scene.getEngine();
  38290. // VBO
  38291. var vertices = [];
  38292. vertices.push(1, 1);
  38293. vertices.push(-1, 1);
  38294. vertices.push(-1, -1);
  38295. vertices.push(1, -1);
  38296. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38297. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38298. // Indices
  38299. var indices = [];
  38300. indices.push(0);
  38301. indices.push(1);
  38302. indices.push(2);
  38303. indices.push(0);
  38304. indices.push(2);
  38305. indices.push(3);
  38306. this._indexBuffer = engine.createIndexBuffer(indices);
  38307. // Effects
  38308. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  38309. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  38310. }
  38311. Object.defineProperty(Layer.prototype, "onDispose", {
  38312. set: function (callback) {
  38313. if (this._onDisposeObserver) {
  38314. this.onDisposeObservable.remove(this._onDisposeObserver);
  38315. }
  38316. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38317. },
  38318. enumerable: true,
  38319. configurable: true
  38320. });
  38321. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  38322. set: function (callback) {
  38323. if (this._onBeforeRenderObserver) {
  38324. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  38325. }
  38326. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  38327. },
  38328. enumerable: true,
  38329. configurable: true
  38330. });
  38331. Object.defineProperty(Layer.prototype, "onAfterRender", {
  38332. set: function (callback) {
  38333. if (this._onAfterRenderObserver) {
  38334. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  38335. }
  38336. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  38337. },
  38338. enumerable: true,
  38339. configurable: true
  38340. });
  38341. Layer.prototype.render = function () {
  38342. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  38343. // Check
  38344. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  38345. return;
  38346. var engine = this._scene.getEngine();
  38347. this.onBeforeRenderObservable.notifyObservers(this);
  38348. // Render
  38349. engine.enableEffect(currentEffect);
  38350. engine.setState(false);
  38351. // Texture
  38352. currentEffect.setTexture("textureSampler", this.texture);
  38353. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  38354. // Color
  38355. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  38356. // Scale / offset
  38357. currentEffect.setVector2("offset", this.offset);
  38358. currentEffect.setVector2("scale", this.scale);
  38359. // VBOs
  38360. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38361. // Draw order
  38362. if (!this.alphaTest) {
  38363. engine.setAlphaMode(this.alphaBlendingMode);
  38364. engine.draw(true, 0, 6);
  38365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38366. }
  38367. else {
  38368. engine.draw(true, 0, 6);
  38369. }
  38370. this.onAfterRenderObservable.notifyObservers(this);
  38371. };
  38372. Layer.prototype.dispose = function () {
  38373. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38374. if (vertexBuffer) {
  38375. vertexBuffer.dispose();
  38376. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38377. }
  38378. if (this._indexBuffer) {
  38379. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38380. this._indexBuffer = null;
  38381. }
  38382. if (this.texture) {
  38383. this.texture.dispose();
  38384. this.texture = null;
  38385. }
  38386. // Remove from scene
  38387. var index = this._scene.layers.indexOf(this);
  38388. this._scene.layers.splice(index, 1);
  38389. // Callback
  38390. this.onDisposeObservable.notifyObservers(this);
  38391. this.onDisposeObservable.clear();
  38392. this.onAfterRenderObservable.clear();
  38393. this.onBeforeRenderObservable.clear();
  38394. };
  38395. return Layer;
  38396. }());
  38397. BABYLON.Layer = Layer;
  38398. })(BABYLON || (BABYLON = {}));
  38399. //# sourceMappingURL=babylon.layer.js.map
  38400. var BABYLON;
  38401. (function (BABYLON) {
  38402. var BlurPostProcess = (function (_super) {
  38403. __extends(BlurPostProcess, _super);
  38404. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  38405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38406. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38407. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  38408. _this.direction = direction;
  38409. _this._packedFloat = false;
  38410. _this.onApplyObservable.add(function (effect) {
  38411. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  38412. });
  38413. _this.kernel = kernel;
  38414. return _this;
  38415. }
  38416. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  38417. /**
  38418. * Gets the length in pixels of the blur sample region
  38419. */
  38420. get: function () {
  38421. return this._idealKernel;
  38422. },
  38423. /**
  38424. * Sets the length in pixels of the blur sample region
  38425. */
  38426. set: function (v) {
  38427. if (this._idealKernel === v) {
  38428. return;
  38429. }
  38430. v = Math.max(v, 1);
  38431. this._idealKernel = v;
  38432. this._kernel = this._nearestBestKernel(v);
  38433. this._updateParameters();
  38434. },
  38435. enumerable: true,
  38436. configurable: true
  38437. });
  38438. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  38439. /**
  38440. * Gets wether or not the blur is unpacking/repacking floats
  38441. */
  38442. get: function () {
  38443. return this._packedFloat;
  38444. },
  38445. /**
  38446. * Sets wether or not the blur needs to unpack/repack floats
  38447. */
  38448. set: function (v) {
  38449. if (this._packedFloat === v) {
  38450. return;
  38451. }
  38452. this._packedFloat = v;
  38453. this._updateParameters();
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. BlurPostProcess.prototype._updateParameters = function () {
  38459. // Generate sampling offsets and weights
  38460. var N = this._kernel;
  38461. var centerIndex = (N - 1) / 2;
  38462. // Generate Gaussian sampling weights over kernel
  38463. var offsets = [];
  38464. var weights = [];
  38465. var totalWeight = 0;
  38466. for (var i = 0; i < N; i++) {
  38467. var u = i / (N - 1);
  38468. var w = this._gaussianWeight(u * 2.0 - 1);
  38469. offsets[i] = (i - centerIndex);
  38470. weights[i] = w;
  38471. totalWeight += w;
  38472. }
  38473. // Normalize weights
  38474. for (var i = 0; i < weights.length; i++) {
  38475. weights[i] /= totalWeight;
  38476. }
  38477. // Optimize: combine samples to take advantage of hardware linear sampling
  38478. // Walk from left to center, combining pairs (symmetrically)
  38479. var linearSamplingWeights = [];
  38480. var linearSamplingOffsets = [];
  38481. var linearSamplingMap = [];
  38482. for (var i = 0; i <= centerIndex; i += 2) {
  38483. var j = Math.min(i + 1, Math.floor(centerIndex));
  38484. var singleCenterSample = i === j;
  38485. if (singleCenterSample) {
  38486. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38487. }
  38488. else {
  38489. var sharedCell = j === centerIndex;
  38490. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  38491. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  38492. if (offsetLinear === 0) {
  38493. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38494. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  38495. }
  38496. else {
  38497. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  38498. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  38499. }
  38500. }
  38501. }
  38502. for (var i = 0; i < linearSamplingMap.length; i++) {
  38503. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  38504. linearSamplingWeights[i] = linearSamplingMap[i].w;
  38505. }
  38506. // Replace with optimized
  38507. offsets = linearSamplingOffsets;
  38508. weights = linearSamplingWeights;
  38509. // Generate shaders
  38510. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  38511. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  38512. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  38513. var defines = "";
  38514. for (var i = 0; i < varyingCount; i++) {
  38515. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  38516. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  38517. }
  38518. var depCount = 0;
  38519. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  38520. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  38521. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  38522. depCount++;
  38523. }
  38524. if (this.packedFloat) {
  38525. defines += "#define PACKEDFLOAT 1";
  38526. }
  38527. this.updateEffect(defines, null, null, {
  38528. varyingCount: varyingCount,
  38529. depCount: depCount
  38530. });
  38531. };
  38532. /**
  38533. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  38534. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  38535. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  38536. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  38537. * The gaps between physical kernels are compensated for in the weighting of the samples
  38538. * @param idealKernel Ideal blur kernel.
  38539. * @return Nearest best kernel.
  38540. */
  38541. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  38542. var v = Math.round(idealKernel);
  38543. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  38544. var k = _a[_i];
  38545. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  38546. return Math.max(k, 3);
  38547. }
  38548. }
  38549. return Math.max(v, 3);
  38550. };
  38551. /**
  38552. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  38553. * @param x The point on the Gaussian distribution to sample.
  38554. * @return the value of the Gaussian function at x.
  38555. */
  38556. BlurPostProcess.prototype._gaussianWeight = function (x) {
  38557. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  38558. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  38559. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  38560. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  38561. // truncated at around 1.3% of peak strength.
  38562. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  38563. var sigma = (1 / 3);
  38564. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  38565. var exponent = -((x * x) / (2.0 * sigma * sigma));
  38566. var weight = (1.0 / denominator) * Math.exp(exponent);
  38567. return weight;
  38568. };
  38569. /**
  38570. * Generates a string that can be used as a floating point number in GLSL.
  38571. * @param x Value to print.
  38572. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  38573. * @return GLSL float string.
  38574. */
  38575. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  38576. if (decimalFigures === void 0) { decimalFigures = 8; }
  38577. return x.toFixed(decimalFigures).replace(/0+$/, '');
  38578. };
  38579. return BlurPostProcess;
  38580. }(BABYLON.PostProcess));
  38581. BABYLON.BlurPostProcess = BlurPostProcess;
  38582. })(BABYLON || (BABYLON = {}));
  38583. //# sourceMappingURL=babylon.blurPostProcess.js.map
  38584. var BABYLON;
  38585. (function (BABYLON) {
  38586. var FxaaPostProcess = (function (_super) {
  38587. __extends(FxaaPostProcess, _super);
  38588. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38589. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38590. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  38591. _this.onApplyObservable.add(function (effect) {
  38592. var texelSize = _this.texelSize;
  38593. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  38594. });
  38595. return _this;
  38596. }
  38597. return FxaaPostProcess;
  38598. }(BABYLON.PostProcess));
  38599. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38600. })(BABYLON || (BABYLON = {}));
  38601. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  38602. var BABYLON;
  38603. (function (BABYLON) {
  38604. var HighlightsPostProcess = (function (_super) {
  38605. __extends(HighlightsPostProcess, _super);
  38606. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38607. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38608. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  38609. }
  38610. return HighlightsPostProcess;
  38611. }(BABYLON.PostProcess));
  38612. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  38613. })(BABYLON || (BABYLON = {}));
  38614. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  38615. var BABYLON;
  38616. (function (BABYLON) {
  38617. var ImageProcessingPostProcess = (function (_super) {
  38618. __extends(ImageProcessingPostProcess, _super);
  38619. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38620. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38621. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  38622. _this._fromLinearSpace = true;
  38623. /**
  38624. * Defines cache preventing GC.
  38625. */
  38626. _this._defines = {
  38627. IMAGEPROCESSING: false,
  38628. VIGNETTE: false,
  38629. VIGNETTEBLENDMODEMULTIPLY: false,
  38630. VIGNETTEBLENDMODEOPAQUE: false,
  38631. TONEMAPPING: false,
  38632. CONTRAST: false,
  38633. COLORCURVES: false,
  38634. COLORGRADING: false,
  38635. FROMLINEARSPACE: false,
  38636. SAMPLER3DGREENDEPTH: false,
  38637. SAMPLER3DBGRMAP: false,
  38638. IMAGEPROCESSINGPOSTPROCESS: false,
  38639. EXPOSURE: false,
  38640. };
  38641. // Setup the default processing configuration to the scene.
  38642. _this._attachImageProcessingConfiguration(null);
  38643. _this.imageProcessingConfiguration.applyByPostProcess = true;
  38644. _this._updateParameters();
  38645. _this.onApply = function (effect) {
  38646. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  38647. };
  38648. return _this;
  38649. }
  38650. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  38651. /**
  38652. * Gets the image processing configuration used either in this material.
  38653. */
  38654. get: function () {
  38655. return this._imageProcessingConfiguration;
  38656. },
  38657. /**
  38658. * Sets the Default image processing configuration used either in the this material.
  38659. *
  38660. * If sets to null, the scene one is in use.
  38661. */
  38662. set: function (value) {
  38663. this._attachImageProcessingConfiguration(value);
  38664. },
  38665. enumerable: true,
  38666. configurable: true
  38667. });
  38668. /**
  38669. * Attaches a new image processing configuration to the PBR Material.
  38670. * @param configuration
  38671. */
  38672. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  38673. var _this = this;
  38674. if (configuration === this._imageProcessingConfiguration) {
  38675. return;
  38676. }
  38677. // Detaches observer.
  38678. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38679. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38680. }
  38681. // Pick the scene configuration if needed.
  38682. if (!configuration) {
  38683. var camera = this.getCamera();
  38684. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  38685. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  38686. }
  38687. else {
  38688. this._imageProcessingConfiguration = configuration;
  38689. }
  38690. // Attaches observer.
  38691. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38692. _this._updateParameters();
  38693. });
  38694. // Ensure the effect will be rebuilt.
  38695. this._updateParameters();
  38696. };
  38697. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  38698. /**
  38699. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  38700. */
  38701. get: function () {
  38702. return this.imageProcessingConfiguration.colorCurves;
  38703. },
  38704. /**
  38705. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  38706. */
  38707. set: function (value) {
  38708. this.imageProcessingConfiguration.colorCurves = value;
  38709. },
  38710. enumerable: true,
  38711. configurable: true
  38712. });
  38713. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  38714. /**
  38715. * Gets wether the color curves effect is enabled.
  38716. */
  38717. get: function () {
  38718. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38719. },
  38720. /**
  38721. * Sets wether the color curves effect is enabled.
  38722. */
  38723. set: function (value) {
  38724. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38725. },
  38726. enumerable: true,
  38727. configurable: true
  38728. });
  38729. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  38730. /**
  38731. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  38732. */
  38733. get: function () {
  38734. return this.imageProcessingConfiguration.colorGradingTexture;
  38735. },
  38736. /**
  38737. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  38738. */
  38739. set: function (value) {
  38740. this.imageProcessingConfiguration.colorGradingTexture = value;
  38741. },
  38742. enumerable: true,
  38743. configurable: true
  38744. });
  38745. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  38746. /**
  38747. * Gets wether the color grading effect is enabled.
  38748. */
  38749. get: function () {
  38750. return this.imageProcessingConfiguration.colorGradingEnabled;
  38751. },
  38752. /**
  38753. * Gets wether the color grading effect is enabled.
  38754. */
  38755. set: function (value) {
  38756. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38757. },
  38758. enumerable: true,
  38759. configurable: true
  38760. });
  38761. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  38762. /**
  38763. * Gets exposure used in the effect.
  38764. */
  38765. get: function () {
  38766. return this.imageProcessingConfiguration.exposure;
  38767. },
  38768. /**
  38769. * Sets exposure used in the effect.
  38770. */
  38771. set: function (value) {
  38772. this.imageProcessingConfiguration.exposure = value;
  38773. },
  38774. enumerable: true,
  38775. configurable: true
  38776. });
  38777. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  38778. /**
  38779. * Gets wether tonemapping is enabled or not.
  38780. */
  38781. get: function () {
  38782. return this._imageProcessingConfiguration.toneMappingEnabled;
  38783. },
  38784. /**
  38785. * Sets wether tonemapping is enabled or not
  38786. */
  38787. set: function (value) {
  38788. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38789. },
  38790. enumerable: true,
  38791. configurable: true
  38792. });
  38793. ;
  38794. ;
  38795. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  38796. /**
  38797. * Gets contrast used in the effect.
  38798. */
  38799. get: function () {
  38800. return this.imageProcessingConfiguration.contrast;
  38801. },
  38802. /**
  38803. * Sets contrast used in the effect.
  38804. */
  38805. set: function (value) {
  38806. this.imageProcessingConfiguration.contrast = value;
  38807. },
  38808. enumerable: true,
  38809. configurable: true
  38810. });
  38811. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  38812. /**
  38813. * Gets Vignette stretch size.
  38814. */
  38815. get: function () {
  38816. return this.imageProcessingConfiguration.vignetteStretch;
  38817. },
  38818. /**
  38819. * Sets Vignette stretch size.
  38820. */
  38821. set: function (value) {
  38822. this.imageProcessingConfiguration.vignetteStretch = value;
  38823. },
  38824. enumerable: true,
  38825. configurable: true
  38826. });
  38827. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  38828. /**
  38829. * Gets Vignette centre X Offset.
  38830. */
  38831. get: function () {
  38832. return this.imageProcessingConfiguration.vignetteCentreX;
  38833. },
  38834. /**
  38835. * Sets Vignette centre X Offset.
  38836. */
  38837. set: function (value) {
  38838. this.imageProcessingConfiguration.vignetteCentreX = value;
  38839. },
  38840. enumerable: true,
  38841. configurable: true
  38842. });
  38843. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  38844. /**
  38845. * Gets Vignette centre Y Offset.
  38846. */
  38847. get: function () {
  38848. return this.imageProcessingConfiguration.vignetteCentreY;
  38849. },
  38850. /**
  38851. * Sets Vignette centre Y Offset.
  38852. */
  38853. set: function (value) {
  38854. this.imageProcessingConfiguration.vignetteCentreY = value;
  38855. },
  38856. enumerable: true,
  38857. configurable: true
  38858. });
  38859. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  38860. /**
  38861. * Gets Vignette weight or intensity of the vignette effect.
  38862. */
  38863. get: function () {
  38864. return this.imageProcessingConfiguration.vignetteWeight;
  38865. },
  38866. /**
  38867. * Sets Vignette weight or intensity of the vignette effect.
  38868. */
  38869. set: function (value) {
  38870. this.imageProcessingConfiguration.vignetteWeight = value;
  38871. },
  38872. enumerable: true,
  38873. configurable: true
  38874. });
  38875. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  38876. /**
  38877. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38878. * if vignetteEnabled is set to true.
  38879. */
  38880. get: function () {
  38881. return this.imageProcessingConfiguration.vignetteColor;
  38882. },
  38883. /**
  38884. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38885. * if vignetteEnabled is set to true.
  38886. */
  38887. set: function (value) {
  38888. this.imageProcessingConfiguration.vignetteColor = value;
  38889. },
  38890. enumerable: true,
  38891. configurable: true
  38892. });
  38893. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  38894. /**
  38895. * Gets Camera field of view used by the Vignette effect.
  38896. */
  38897. get: function () {
  38898. return this.imageProcessingConfiguration.vignetteCameraFov;
  38899. },
  38900. /**
  38901. * Sets Camera field of view used by the Vignette effect.
  38902. */
  38903. set: function (value) {
  38904. this.imageProcessingConfiguration.vignetteCameraFov = value;
  38905. },
  38906. enumerable: true,
  38907. configurable: true
  38908. });
  38909. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  38910. /**
  38911. * Gets the vignette blend mode allowing different kind of effect.
  38912. */
  38913. get: function () {
  38914. return this.imageProcessingConfiguration.vignetteBlendMode;
  38915. },
  38916. /**
  38917. * Sets the vignette blend mode allowing different kind of effect.
  38918. */
  38919. set: function (value) {
  38920. this.imageProcessingConfiguration.vignetteBlendMode = value;
  38921. },
  38922. enumerable: true,
  38923. configurable: true
  38924. });
  38925. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  38926. /**
  38927. * Gets wether the vignette effect is enabled.
  38928. */
  38929. get: function () {
  38930. return this.imageProcessingConfiguration.vignetteEnabled;
  38931. },
  38932. /**
  38933. * Sets wether the vignette effect is enabled.
  38934. */
  38935. set: function (value) {
  38936. this.imageProcessingConfiguration.vignetteEnabled = value;
  38937. },
  38938. enumerable: true,
  38939. configurable: true
  38940. });
  38941. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  38942. /**
  38943. * Gets wether the input of the processing is in Gamma or Linear Space.
  38944. */
  38945. get: function () {
  38946. return this._fromLinearSpace;
  38947. },
  38948. /**
  38949. * Sets wether the input of the processing is in Gamma or Linear Space.
  38950. */
  38951. set: function (value) {
  38952. if (this._fromLinearSpace === value) {
  38953. return;
  38954. }
  38955. this._fromLinearSpace = value;
  38956. this._updateParameters();
  38957. },
  38958. enumerable: true,
  38959. configurable: true
  38960. });
  38961. ImageProcessingPostProcess.prototype._updateParameters = function () {
  38962. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  38963. this.imageProcessingConfiguration.prepareDefines(this._defines);
  38964. var defines = "";
  38965. for (var define in this._defines) {
  38966. if (this._defines[define]) {
  38967. defines += "#define " + define + ";\r\n";
  38968. }
  38969. }
  38970. var samplers = ["textureSampler"];
  38971. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  38972. var uniforms = ["scale"];
  38973. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  38974. this.updateEffect(defines, uniforms, samplers);
  38975. };
  38976. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  38977. _super.prototype.dispose.call(this, camera);
  38978. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38979. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38980. }
  38981. this.imageProcessingConfiguration.applyByPostProcess = false;
  38982. };
  38983. return ImageProcessingPostProcess;
  38984. }(BABYLON.PostProcess));
  38985. __decorate([
  38986. BABYLON.serialize()
  38987. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  38988. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  38989. })(BABYLON || (BABYLON = {}));
  38990. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  38991. var BABYLON;
  38992. (function (BABYLON) {
  38993. /**
  38994. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38995. * It can help converting any input color in a desired output one. This can then be used to create effects
  38996. * from sepia, black and white to sixties or futuristic rendering...
  38997. *
  38998. * The only supported format is currently 3dl.
  38999. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  39000. */
  39001. var ColorGradingTexture = (function (_super) {
  39002. __extends(ColorGradingTexture, _super);
  39003. /**
  39004. * Instantiates a ColorGradingTexture from the following parameters.
  39005. *
  39006. * @param url The location of the color gradind data (currently only supporting 3dl)
  39007. * @param scene The scene the texture will be used in
  39008. */
  39009. function ColorGradingTexture(url, scene) {
  39010. var _this = _super.call(this, scene) || this;
  39011. if (!url) {
  39012. return _this;
  39013. }
  39014. _this._textureMatrix = BABYLON.Matrix.Identity();
  39015. _this.name = url;
  39016. _this.url = url;
  39017. _this.hasAlpha = false;
  39018. _this.isCube = false;
  39019. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39020. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39021. _this.anisotropicFilteringLevel = 1;
  39022. _this._texture = _this._getFromCache(url, true);
  39023. if (!_this._texture) {
  39024. if (!scene.useDelayedTextureLoading) {
  39025. _this.loadTexture();
  39026. }
  39027. else {
  39028. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39029. }
  39030. }
  39031. return _this;
  39032. }
  39033. /**
  39034. * Returns the texture matrix used in most of the material.
  39035. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  39036. */
  39037. ColorGradingTexture.prototype.getTextureMatrix = function () {
  39038. return this._textureMatrix;
  39039. };
  39040. /**
  39041. * Occurs when the file being loaded is a .3dl LUT file.
  39042. */
  39043. ColorGradingTexture.prototype.load3dlTexture = function () {
  39044. var _this = this;
  39045. var mipLevels = 0;
  39046. var floatArrayView = null;
  39047. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39048. this._texture = texture;
  39049. var callback = function (text) {
  39050. var data;
  39051. var tempData;
  39052. var line;
  39053. var lines = text.split('\n');
  39054. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  39055. var maxColor = 0;
  39056. for (var i = 0; i < lines.length; i++) {
  39057. line = lines[i];
  39058. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  39059. continue;
  39060. if (line.indexOf('#') === 0)
  39061. continue;
  39062. var words = line.split(" ");
  39063. if (size === 0) {
  39064. // Number of space + one
  39065. size = words.length;
  39066. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  39067. tempData = new Float32Array(size * size * size * 4);
  39068. continue;
  39069. }
  39070. if (size != 0) {
  39071. var r = Math.max(parseInt(words[0]), 0);
  39072. var g = Math.max(parseInt(words[1]), 0);
  39073. var b = Math.max(parseInt(words[2]), 0);
  39074. maxColor = Math.max(r, maxColor);
  39075. maxColor = Math.max(g, maxColor);
  39076. maxColor = Math.max(b, maxColor);
  39077. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  39078. tempData[pixelStorageIndex + 0] = r;
  39079. tempData[pixelStorageIndex + 1] = g;
  39080. tempData[pixelStorageIndex + 2] = b;
  39081. pixelIndexSlice++;
  39082. if (pixelIndexSlice % size == 0) {
  39083. pixelIndexH++;
  39084. pixelIndexSlice = 0;
  39085. if (pixelIndexH % size == 0) {
  39086. pixelIndexW++;
  39087. pixelIndexH = 0;
  39088. }
  39089. }
  39090. }
  39091. }
  39092. for (var i = 0; i < tempData.length; i++) {
  39093. if (i > 0 && (i + 1) % 4 === 0) {
  39094. data[i] = 255;
  39095. }
  39096. else {
  39097. var value = tempData[i];
  39098. data[i] = (value / maxColor * 255);
  39099. }
  39100. }
  39101. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  39102. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  39103. };
  39104. BABYLON.Tools.LoadFile(this.url, callback);
  39105. return this._texture;
  39106. };
  39107. /**
  39108. * Starts the loading process of the texture.
  39109. */
  39110. ColorGradingTexture.prototype.loadTexture = function () {
  39111. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  39112. this.load3dlTexture();
  39113. }
  39114. };
  39115. /**
  39116. * Clones the color gradind texture.
  39117. */
  39118. ColorGradingTexture.prototype.clone = function () {
  39119. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  39120. // Base texture
  39121. newTexture.level = this.level;
  39122. return newTexture;
  39123. };
  39124. /**
  39125. * Called during delayed load for textures.
  39126. */
  39127. ColorGradingTexture.prototype.delayLoad = function () {
  39128. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39129. return;
  39130. }
  39131. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39132. this._texture = this._getFromCache(this.url, true);
  39133. if (!this._texture) {
  39134. this.loadTexture();
  39135. }
  39136. };
  39137. /**
  39138. * Parses a color grading texture serialized by Babylon.
  39139. * @param parsedTexture The texture information being parsedTexture
  39140. * @param scene The scene to load the texture in
  39141. * @param rootUrl The root url of the data assets to load
  39142. * @return A color gradind texture
  39143. */
  39144. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39145. var texture = null;
  39146. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39147. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  39148. texture.name = parsedTexture.name;
  39149. texture.level = parsedTexture.level;
  39150. }
  39151. return texture;
  39152. };
  39153. /**
  39154. * Serializes the LUT texture to json format.
  39155. */
  39156. ColorGradingTexture.prototype.serialize = function () {
  39157. if (!this.name) {
  39158. return null;
  39159. }
  39160. var serializationObject = {};
  39161. serializationObject.name = this.name;
  39162. serializationObject.level = this.level;
  39163. serializationObject.customType = "BABYLON.ColorGradingTexture";
  39164. return serializationObject;
  39165. };
  39166. return ColorGradingTexture;
  39167. }(BABYLON.BaseTexture));
  39168. /**
  39169. * Empty line regex stored for GC.
  39170. */
  39171. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  39172. BABYLON.ColorGradingTexture = ColorGradingTexture;
  39173. })(BABYLON || (BABYLON = {}));
  39174. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  39175. var BABYLON;
  39176. (function (BABYLON) {
  39177. /**
  39178. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39179. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39180. * 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;
  39181. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39182. */
  39183. var ColorCurves = (function () {
  39184. function ColorCurves() {
  39185. this._dirty = true;
  39186. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  39187. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  39188. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39189. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  39190. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39191. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  39192. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  39193. this._globalHue = 30;
  39194. this._globalDensity = 0;
  39195. this._globalSaturation = 0;
  39196. this._globalExposure = 0;
  39197. this._highlightsHue = 30;
  39198. this._highlightsDensity = 0;
  39199. this._highlightsSaturation = 0;
  39200. this._highlightsExposure = 0;
  39201. this._midtonesHue = 30;
  39202. this._midtonesDensity = 0;
  39203. this._midtonesSaturation = 0;
  39204. this._midtonesExposure = 0;
  39205. this._shadowsHue = 30;
  39206. this._shadowsDensity = 0;
  39207. this._shadowsSaturation = 0;
  39208. this._shadowsExposure = 0;
  39209. }
  39210. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  39211. /**
  39212. * Gets the global Hue value.
  39213. * 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).
  39214. */
  39215. get: function () {
  39216. return this._globalHue;
  39217. },
  39218. /**
  39219. * Sets the global Hue value.
  39220. * 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).
  39221. */
  39222. set: function (value) {
  39223. this._globalHue = value;
  39224. this._dirty = true;
  39225. },
  39226. enumerable: true,
  39227. configurable: true
  39228. });
  39229. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  39230. /**
  39231. * Gets the global Density value.
  39232. * 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.
  39233. * Values less than zero provide a filter of opposite hue.
  39234. */
  39235. get: function () {
  39236. return this._globalDensity;
  39237. },
  39238. /**
  39239. * Sets the global Density value.
  39240. * 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.
  39241. * Values less than zero provide a filter of opposite hue.
  39242. */
  39243. set: function (value) {
  39244. this._globalDensity = value;
  39245. this._dirty = true;
  39246. },
  39247. enumerable: true,
  39248. configurable: true
  39249. });
  39250. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  39251. /**
  39252. * Gets the global Saturation value.
  39253. * 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.
  39254. */
  39255. get: function () {
  39256. return this._globalSaturation;
  39257. },
  39258. /**
  39259. * Sets the global Saturation value.
  39260. * 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.
  39261. */
  39262. set: function (value) {
  39263. this._globalSaturation = value;
  39264. this._dirty = true;
  39265. },
  39266. enumerable: true,
  39267. configurable: true
  39268. });
  39269. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  39270. /**
  39271. * Gets the highlights Hue value.
  39272. * 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).
  39273. */
  39274. get: function () {
  39275. return this._highlightsHue;
  39276. },
  39277. /**
  39278. * Sets the highlights Hue value.
  39279. * 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).
  39280. */
  39281. set: function (value) {
  39282. this._highlightsHue = value;
  39283. this._dirty = true;
  39284. },
  39285. enumerable: true,
  39286. configurable: true
  39287. });
  39288. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  39289. /**
  39290. * Gets the highlights Density value.
  39291. * 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.
  39292. * Values less than zero provide a filter of opposite hue.
  39293. */
  39294. get: function () {
  39295. return this._highlightsDensity;
  39296. },
  39297. /**
  39298. * Sets the highlights Density value.
  39299. * 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.
  39300. * Values less than zero provide a filter of opposite hue.
  39301. */
  39302. set: function (value) {
  39303. this._highlightsDensity = value;
  39304. this._dirty = true;
  39305. },
  39306. enumerable: true,
  39307. configurable: true
  39308. });
  39309. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  39310. /**
  39311. * Gets the highlights Saturation value.
  39312. * 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.
  39313. */
  39314. get: function () {
  39315. return this._highlightsSaturation;
  39316. },
  39317. /**
  39318. * Sets the highlights Saturation value.
  39319. * 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.
  39320. */
  39321. set: function (value) {
  39322. this._highlightsSaturation = value;
  39323. this._dirty = true;
  39324. },
  39325. enumerable: true,
  39326. configurable: true
  39327. });
  39328. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  39329. /**
  39330. * Gets the highlights Exposure value.
  39331. * 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.
  39332. */
  39333. get: function () {
  39334. return this._highlightsExposure;
  39335. },
  39336. /**
  39337. * Sets the highlights Exposure value.
  39338. * 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.
  39339. */
  39340. set: function (value) {
  39341. this._highlightsExposure = value;
  39342. this._dirty = true;
  39343. },
  39344. enumerable: true,
  39345. configurable: true
  39346. });
  39347. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  39348. /**
  39349. * Gets the midtones Hue value.
  39350. * 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).
  39351. */
  39352. get: function () {
  39353. return this._midtonesHue;
  39354. },
  39355. /**
  39356. * Sets the midtones Hue value.
  39357. * 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).
  39358. */
  39359. set: function (value) {
  39360. this._midtonesHue = value;
  39361. this._dirty = true;
  39362. },
  39363. enumerable: true,
  39364. configurable: true
  39365. });
  39366. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  39367. /**
  39368. * Gets the midtones Density value.
  39369. * 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.
  39370. * Values less than zero provide a filter of opposite hue.
  39371. */
  39372. get: function () {
  39373. return this._midtonesDensity;
  39374. },
  39375. /**
  39376. * Sets the midtones Density value.
  39377. * 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.
  39378. * Values less than zero provide a filter of opposite hue.
  39379. */
  39380. set: function (value) {
  39381. this._midtonesDensity = value;
  39382. this._dirty = true;
  39383. },
  39384. enumerable: true,
  39385. configurable: true
  39386. });
  39387. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  39388. /**
  39389. * Gets the midtones Saturation value.
  39390. * 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.
  39391. */
  39392. get: function () {
  39393. return this._midtonesSaturation;
  39394. },
  39395. /**
  39396. * Sets the midtones Saturation value.
  39397. * 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.
  39398. */
  39399. set: function (value) {
  39400. this._midtonesSaturation = value;
  39401. this._dirty = true;
  39402. },
  39403. enumerable: true,
  39404. configurable: true
  39405. });
  39406. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  39407. /**
  39408. * Gets the midtones Exposure value.
  39409. * 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.
  39410. */
  39411. get: function () {
  39412. return this._midtonesExposure;
  39413. },
  39414. /**
  39415. * Sets the midtones Exposure value.
  39416. * 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.
  39417. */
  39418. set: function (value) {
  39419. this._midtonesExposure = value;
  39420. this._dirty = true;
  39421. },
  39422. enumerable: true,
  39423. configurable: true
  39424. });
  39425. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  39426. /**
  39427. * Gets the shadows Hue value.
  39428. * 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).
  39429. */
  39430. get: function () {
  39431. return this._shadowsHue;
  39432. },
  39433. /**
  39434. * Sets the shadows Hue value.
  39435. * 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).
  39436. */
  39437. set: function (value) {
  39438. this._shadowsHue = value;
  39439. this._dirty = true;
  39440. },
  39441. enumerable: true,
  39442. configurable: true
  39443. });
  39444. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  39445. /**
  39446. * Gets the shadows Density value.
  39447. * 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.
  39448. * Values less than zero provide a filter of opposite hue.
  39449. */
  39450. get: function () {
  39451. return this._shadowsDensity;
  39452. },
  39453. /**
  39454. * Sets the shadows Density value.
  39455. * 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.
  39456. * Values less than zero provide a filter of opposite hue.
  39457. */
  39458. set: function (value) {
  39459. this._shadowsDensity = value;
  39460. this._dirty = true;
  39461. },
  39462. enumerable: true,
  39463. configurable: true
  39464. });
  39465. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  39466. /**
  39467. * Gets the shadows Saturation value.
  39468. * 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.
  39469. */
  39470. get: function () {
  39471. return this._shadowsSaturation;
  39472. },
  39473. /**
  39474. * Sets the shadows Saturation value.
  39475. * 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.
  39476. */
  39477. set: function (value) {
  39478. this._shadowsSaturation = value;
  39479. this._dirty = true;
  39480. },
  39481. enumerable: true,
  39482. configurable: true
  39483. });
  39484. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  39485. /**
  39486. * Gets the shadows Exposure value.
  39487. * 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.
  39488. */
  39489. get: function () {
  39490. return this._shadowsExposure;
  39491. },
  39492. /**
  39493. * Sets the shadows Exposure value.
  39494. * 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.
  39495. */
  39496. set: function (value) {
  39497. this._shadowsExposure = value;
  39498. this._dirty = true;
  39499. },
  39500. enumerable: true,
  39501. configurable: true
  39502. });
  39503. /**
  39504. * Binds the color curves to the shader.
  39505. * @param colorCurves The color curve to bind
  39506. * @param effect The effect to bind to
  39507. */
  39508. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  39509. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  39510. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  39511. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  39512. if (colorCurves._dirty) {
  39513. colorCurves._dirty = false;
  39514. // Fill in global info.
  39515. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  39516. // Compute highlights info.
  39517. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  39518. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  39519. // Compute midtones info.
  39520. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  39521. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  39522. // Compute shadows info.
  39523. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  39524. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  39525. // Compute deltas (neutral is midtones).
  39526. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  39527. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  39528. }
  39529. if (effect) {
  39530. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  39531. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  39532. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  39533. }
  39534. };
  39535. /**
  39536. * Prepare the list of uniforms associated with the ColorCurves effects.
  39537. * @param uniformsList The list of uniforms used in the effect
  39538. */
  39539. ColorCurves.PrepareUniforms = function (uniformsList) {
  39540. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  39541. };
  39542. /**
  39543. * Returns color grading data based on a hue, density, saturation and exposure value.
  39544. * @param filterHue The hue of the color filter.
  39545. * @param filterDensity The density of the color filter.
  39546. * @param saturation The saturation.
  39547. * @param exposure The exposure.
  39548. * @param result The result data container.
  39549. */
  39550. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  39551. if (hue == null) {
  39552. return;
  39553. }
  39554. hue = ColorCurves.clamp(hue, 0, 360);
  39555. density = ColorCurves.clamp(density, -100, 100);
  39556. saturation = ColorCurves.clamp(saturation, -100, 100);
  39557. exposure = ColorCurves.clamp(exposure, -100, 100);
  39558. // Remap the slider/config filter density with non-linear mapping and also scale by half
  39559. // so that the maximum filter density is only 50% control. This provides fine control
  39560. // for small values and reasonable range.
  39561. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  39562. density *= 0.5;
  39563. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  39564. if (density < 0) {
  39565. density *= -1;
  39566. hue = (hue + 180) % 360;
  39567. }
  39568. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  39569. result.scaleToRef(2, result);
  39570. result.a = 1 + 0.01 * saturation;
  39571. };
  39572. /**
  39573. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  39574. * @param value The input slider value in range [-100,100].
  39575. * @returns Adjusted value.
  39576. */
  39577. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  39578. value /= 100;
  39579. var x = Math.abs(value);
  39580. x = Math.pow(x, 2);
  39581. if (value < 0) {
  39582. x *= -1;
  39583. }
  39584. x *= 100;
  39585. return x;
  39586. };
  39587. /**
  39588. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  39589. * @param hue The hue (H) input.
  39590. * @param saturation The saturation (S) input.
  39591. * @param brightness The brightness (B) input.
  39592. * @result An RGBA color represented as Vector4.
  39593. */
  39594. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  39595. var h = ColorCurves.clamp(hue, 0, 360);
  39596. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  39597. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  39598. if (s === 0) {
  39599. result.r = v;
  39600. result.g = v;
  39601. result.b = v;
  39602. }
  39603. else {
  39604. // sector 0 to 5
  39605. h /= 60;
  39606. var i = Math.floor(h);
  39607. // fractional part of h
  39608. var f = h - i;
  39609. var p = v * (1 - s);
  39610. var q = v * (1 - s * f);
  39611. var t = v * (1 - s * (1 - f));
  39612. switch (i) {
  39613. case 0:
  39614. result.r = v;
  39615. result.g = t;
  39616. result.b = p;
  39617. break;
  39618. case 1:
  39619. result.r = q;
  39620. result.g = v;
  39621. result.b = p;
  39622. break;
  39623. case 2:
  39624. result.r = p;
  39625. result.g = v;
  39626. result.b = t;
  39627. break;
  39628. case 3:
  39629. result.r = p;
  39630. result.g = q;
  39631. result.b = v;
  39632. break;
  39633. case 4:
  39634. result.r = t;
  39635. result.g = p;
  39636. result.b = v;
  39637. break;
  39638. default:
  39639. result.r = v;
  39640. result.g = p;
  39641. result.b = q;
  39642. break;
  39643. }
  39644. }
  39645. result.a = 1;
  39646. };
  39647. /**
  39648. * Returns a value clamped between min and max
  39649. * @param value The value to clamp
  39650. * @param min The minimum of value
  39651. * @param max The maximum of value
  39652. * @returns The clamped value.
  39653. */
  39654. ColorCurves.clamp = function (value, min, max) {
  39655. return Math.min(Math.max(value, min), max);
  39656. };
  39657. /**
  39658. * Clones the current color curve instance.
  39659. * @return The cloned curves
  39660. */
  39661. ColorCurves.prototype.clone = function () {
  39662. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  39663. };
  39664. /**
  39665. * Serializes the current color curve instance to a json representation.
  39666. * @return a JSON representation
  39667. */
  39668. ColorCurves.prototype.serialize = function () {
  39669. return BABYLON.SerializationHelper.Serialize(this);
  39670. };
  39671. /**
  39672. * Parses the color curve from a json representation.
  39673. * @param source the JSON source to parse
  39674. * @return The parsed curves
  39675. */
  39676. ColorCurves.Parse = function (source) {
  39677. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  39678. };
  39679. return ColorCurves;
  39680. }());
  39681. __decorate([
  39682. BABYLON.serialize()
  39683. ], ColorCurves.prototype, "_globalHue", void 0);
  39684. __decorate([
  39685. BABYLON.serialize()
  39686. ], ColorCurves.prototype, "_globalDensity", void 0);
  39687. __decorate([
  39688. BABYLON.serialize()
  39689. ], ColorCurves.prototype, "_globalSaturation", void 0);
  39690. __decorate([
  39691. BABYLON.serialize()
  39692. ], ColorCurves.prototype, "_globalExposure", void 0);
  39693. __decorate([
  39694. BABYLON.serialize()
  39695. ], ColorCurves.prototype, "_highlightsHue", void 0);
  39696. __decorate([
  39697. BABYLON.serialize()
  39698. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  39699. __decorate([
  39700. BABYLON.serialize()
  39701. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  39702. __decorate([
  39703. BABYLON.serialize()
  39704. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  39705. __decorate([
  39706. BABYLON.serialize()
  39707. ], ColorCurves.prototype, "_midtonesHue", void 0);
  39708. __decorate([
  39709. BABYLON.serialize()
  39710. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  39711. __decorate([
  39712. BABYLON.serialize()
  39713. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  39714. __decorate([
  39715. BABYLON.serialize()
  39716. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  39717. BABYLON.ColorCurves = ColorCurves;
  39718. })(BABYLON || (BABYLON = {}));
  39719. //# sourceMappingURL=babylon.colorCurves.js.map
  39720. var BABYLON;
  39721. (function (BABYLON) {
  39722. var PostProcessRenderPipelineManager = (function () {
  39723. function PostProcessRenderPipelineManager() {
  39724. this._renderPipelines = {};
  39725. }
  39726. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39727. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39728. };
  39729. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39730. var renderPipeline = this._renderPipelines[renderPipelineName];
  39731. if (!renderPipeline) {
  39732. return;
  39733. }
  39734. renderPipeline._attachCameras(cameras, unique);
  39735. };
  39736. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39737. var renderPipeline = this._renderPipelines[renderPipelineName];
  39738. if (!renderPipeline) {
  39739. return;
  39740. }
  39741. renderPipeline._detachCameras(cameras);
  39742. };
  39743. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39744. var renderPipeline = this._renderPipelines[renderPipelineName];
  39745. if (!renderPipeline) {
  39746. return;
  39747. }
  39748. renderPipeline._enableEffect(renderEffectName, cameras);
  39749. };
  39750. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39751. var renderPipeline = this._renderPipelines[renderPipelineName];
  39752. if (!renderPipeline) {
  39753. return;
  39754. }
  39755. renderPipeline._disableEffect(renderEffectName, cameras);
  39756. };
  39757. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39758. var renderPipeline = this._renderPipelines[renderPipelineName];
  39759. if (!renderPipeline) {
  39760. return;
  39761. }
  39762. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39763. };
  39764. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39765. var renderPipeline = this._renderPipelines[renderPipelineName];
  39766. if (!renderPipeline) {
  39767. return;
  39768. }
  39769. renderPipeline._disableDisplayOnlyPass(cameras);
  39770. };
  39771. PostProcessRenderPipelineManager.prototype.update = function () {
  39772. for (var renderPipelineName in this._renderPipelines) {
  39773. var pipeline = this._renderPipelines[renderPipelineName];
  39774. if (!pipeline.isSupported) {
  39775. pipeline.dispose();
  39776. delete this._renderPipelines[renderPipelineName];
  39777. }
  39778. else {
  39779. pipeline._update();
  39780. }
  39781. }
  39782. };
  39783. return PostProcessRenderPipelineManager;
  39784. }());
  39785. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39786. })(BABYLON || (BABYLON = {}));
  39787. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39788. var BABYLON;
  39789. (function (BABYLON) {
  39790. var PostProcessRenderPass = (function () {
  39791. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39792. this._enabled = true;
  39793. this._refCount = 0;
  39794. this._name = name;
  39795. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39796. this.setRenderList(renderList);
  39797. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39798. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39799. this._scene = scene;
  39800. this._renderList = renderList;
  39801. }
  39802. // private
  39803. PostProcessRenderPass.prototype._incRefCount = function () {
  39804. if (this._refCount === 0) {
  39805. this._scene.customRenderTargets.push(this._renderTexture);
  39806. }
  39807. return ++this._refCount;
  39808. };
  39809. PostProcessRenderPass.prototype._decRefCount = function () {
  39810. this._refCount--;
  39811. if (this._refCount <= 0) {
  39812. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39813. }
  39814. return this._refCount;
  39815. };
  39816. PostProcessRenderPass.prototype._update = function () {
  39817. this.setRenderList(this._renderList);
  39818. };
  39819. // public
  39820. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39821. this._renderTexture.renderList = renderList;
  39822. };
  39823. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39824. return this._renderTexture;
  39825. };
  39826. return PostProcessRenderPass;
  39827. }());
  39828. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39829. })(BABYLON || (BABYLON = {}));
  39830. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39831. var BABYLON;
  39832. (function (BABYLON) {
  39833. var PostProcessRenderEffect = (function () {
  39834. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39835. this._engine = engine;
  39836. this._name = name;
  39837. this._singleInstance = singleInstance || true;
  39838. this._getPostProcess = getPostProcess;
  39839. this._cameras = [];
  39840. this._indicesForCamera = [];
  39841. this._postProcesses = {};
  39842. this._renderPasses = {};
  39843. this._renderEffectAsPasses = {};
  39844. }
  39845. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39846. get: function () {
  39847. for (var index in this._postProcesses) {
  39848. if (!this._postProcesses[index].isSupported) {
  39849. return false;
  39850. }
  39851. }
  39852. return true;
  39853. },
  39854. enumerable: true,
  39855. configurable: true
  39856. });
  39857. PostProcessRenderEffect.prototype._update = function () {
  39858. for (var renderPassName in this._renderPasses) {
  39859. this._renderPasses[renderPassName]._update();
  39860. }
  39861. };
  39862. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39863. this._renderPasses[renderPass._name] = renderPass;
  39864. this._linkParameters();
  39865. };
  39866. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39867. delete this._renderPasses[renderPass._name];
  39868. this._linkParameters();
  39869. };
  39870. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39871. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39872. this._linkParameters();
  39873. };
  39874. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39875. for (var renderPassName in this._renderPasses) {
  39876. if (renderPassName === passName) {
  39877. return this._renderPasses[passName];
  39878. }
  39879. }
  39880. };
  39881. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39882. this._renderPasses = {};
  39883. this._linkParameters();
  39884. };
  39885. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39886. var cameraKey;
  39887. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39888. for (var i = 0; i < _cam.length; i++) {
  39889. var camera = _cam[i];
  39890. var cameraName = camera.name;
  39891. if (this._singleInstance) {
  39892. cameraKey = 0;
  39893. }
  39894. else {
  39895. cameraKey = cameraName;
  39896. }
  39897. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39898. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39899. if (!this._indicesForCamera[cameraName]) {
  39900. this._indicesForCamera[cameraName] = [];
  39901. }
  39902. this._indicesForCamera[cameraName].push(index);
  39903. if (this._cameras.indexOf(camera) === -1) {
  39904. this._cameras[cameraName] = camera;
  39905. }
  39906. for (var passName in this._renderPasses) {
  39907. this._renderPasses[passName]._incRefCount();
  39908. }
  39909. }
  39910. this._linkParameters();
  39911. };
  39912. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39913. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39914. for (var i = 0; i < _cam.length; i++) {
  39915. var camera = _cam[i];
  39916. var cameraName = camera.name;
  39917. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39918. var index = this._cameras.indexOf(cameraName);
  39919. this._indicesForCamera.splice(index, 1);
  39920. this._cameras.splice(index, 1);
  39921. for (var passName in this._renderPasses) {
  39922. this._renderPasses[passName]._decRefCount();
  39923. }
  39924. }
  39925. };
  39926. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39927. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39928. for (var i = 0; i < _cam.length; i++) {
  39929. var camera = _cam[i];
  39930. var cameraName = camera.name;
  39931. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39932. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39933. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39934. }
  39935. }
  39936. for (var passName in this._renderPasses) {
  39937. this._renderPasses[passName]._incRefCount();
  39938. }
  39939. }
  39940. };
  39941. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39942. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39943. for (var i = 0; i < _cam.length; i++) {
  39944. var camera = _cam[i];
  39945. var cameraName = camera.Name;
  39946. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39947. for (var passName in this._renderPasses) {
  39948. this._renderPasses[passName]._decRefCount();
  39949. }
  39950. }
  39951. };
  39952. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39953. if (this._singleInstance) {
  39954. return this._postProcesses[0];
  39955. }
  39956. else {
  39957. return this._postProcesses[camera.name];
  39958. }
  39959. };
  39960. PostProcessRenderEffect.prototype._linkParameters = function () {
  39961. var _this = this;
  39962. for (var index in this._postProcesses) {
  39963. if (this.applyParameters) {
  39964. this.applyParameters(this._postProcesses[index]);
  39965. }
  39966. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39967. _this._linkTextures(effect);
  39968. });
  39969. }
  39970. };
  39971. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39972. for (var renderPassName in this._renderPasses) {
  39973. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39974. }
  39975. for (var renderEffectName in this._renderEffectAsPasses) {
  39976. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39977. }
  39978. };
  39979. return PostProcessRenderEffect;
  39980. }());
  39981. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39982. })(BABYLON || (BABYLON = {}));
  39983. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39984. var BABYLON;
  39985. (function (BABYLON) {
  39986. var PostProcessRenderPipeline = (function () {
  39987. function PostProcessRenderPipeline(engine, name) {
  39988. this._engine = engine;
  39989. this._name = name;
  39990. this._renderEffects = new Array();
  39991. this._renderEffectsForIsolatedPass = new Array();
  39992. this._cameras = [];
  39993. }
  39994. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39995. get: function () {
  39996. for (var renderEffectName in this._renderEffects) {
  39997. if (!this._renderEffects[renderEffectName].isSupported) {
  39998. return false;
  39999. }
  40000. }
  40001. return true;
  40002. },
  40003. enumerable: true,
  40004. configurable: true
  40005. });
  40006. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  40007. this._renderEffects[renderEffect._name] = renderEffect;
  40008. };
  40009. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  40010. var renderEffects = this._renderEffects[renderEffectName];
  40011. if (!renderEffects) {
  40012. return;
  40013. }
  40014. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40015. };
  40016. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  40017. var renderEffects = this._renderEffects[renderEffectName];
  40018. if (!renderEffects) {
  40019. return;
  40020. }
  40021. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40022. };
  40023. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  40024. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40025. var indicesToDelete = [];
  40026. var i;
  40027. for (i = 0; i < _cam.length; i++) {
  40028. var camera = _cam[i];
  40029. var cameraName = camera.name;
  40030. if (this._cameras.indexOf(camera) === -1) {
  40031. this._cameras[cameraName] = camera;
  40032. }
  40033. else if (unique) {
  40034. indicesToDelete.push(i);
  40035. }
  40036. }
  40037. for (i = 0; i < indicesToDelete.length; i++) {
  40038. cameras.splice(indicesToDelete[i], 1);
  40039. }
  40040. for (var renderEffectName in this._renderEffects) {
  40041. this._renderEffects[renderEffectName]._attachCameras(_cam);
  40042. }
  40043. };
  40044. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  40045. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40046. for (var renderEffectName in this._renderEffects) {
  40047. this._renderEffects[renderEffectName]._detachCameras(_cam);
  40048. }
  40049. for (var i = 0; i < _cam.length; i++) {
  40050. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  40051. }
  40052. };
  40053. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  40054. var _this = this;
  40055. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40056. var pass = null;
  40057. var renderEffectName;
  40058. for (renderEffectName in this._renderEffects) {
  40059. pass = this._renderEffects[renderEffectName].getPass(passName);
  40060. if (pass != null) {
  40061. break;
  40062. }
  40063. }
  40064. if (pass === null) {
  40065. return;
  40066. }
  40067. for (renderEffectName in this._renderEffects) {
  40068. this._renderEffects[renderEffectName]._disable(_cam);
  40069. }
  40070. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  40071. for (var i = 0; i < _cam.length; i++) {
  40072. var camera = _cam[i];
  40073. var cameraName = camera.name;
  40074. 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); });
  40075. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  40076. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  40077. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  40078. }
  40079. };
  40080. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  40081. var _this = this;
  40082. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40083. for (var i = 0; i < _cam.length; i++) {
  40084. var camera = _cam[i];
  40085. var cameraName = camera.name;
  40086. 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); });
  40087. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  40088. }
  40089. for (var renderEffectName in this._renderEffects) {
  40090. this._renderEffects[renderEffectName]._enable(_cam);
  40091. }
  40092. };
  40093. PostProcessRenderPipeline.prototype._update = function () {
  40094. for (var renderEffectName in this._renderEffects) {
  40095. this._renderEffects[renderEffectName]._update();
  40096. }
  40097. for (var i = 0; i < this._cameras.length; i++) {
  40098. var cameraName = this._cameras[i].name;
  40099. if (this._renderEffectsForIsolatedPass[cameraName]) {
  40100. this._renderEffectsForIsolatedPass[cameraName]._update();
  40101. }
  40102. }
  40103. };
  40104. PostProcessRenderPipeline.prototype._reset = function () {
  40105. this._renderEffects = new Array();
  40106. this._renderEffectsForIsolatedPass = new Array();
  40107. };
  40108. PostProcessRenderPipeline.prototype.dispose = function () {
  40109. // Must be implemented by children
  40110. };
  40111. return PostProcessRenderPipeline;
  40112. }());
  40113. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  40114. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  40115. __decorate([
  40116. BABYLON.serialize()
  40117. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  40118. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  40119. })(BABYLON || (BABYLON = {}));
  40120. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  40121. var BABYLON;
  40122. (function (BABYLON) {
  40123. var DefaultRenderingPipeline = (function (_super) {
  40124. __extends(DefaultRenderingPipeline, _super);
  40125. /**
  40126. * @constructor
  40127. * @param {string} name - The rendering pipeline name
  40128. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40129. * @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)
  40130. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40131. */
  40132. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  40133. var _this = _super.call(this, scene.getEngine(), name) || this;
  40134. _this.PassPostProcessId = "PassPostProcessEffect";
  40135. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  40136. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  40137. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  40138. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  40139. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  40140. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  40141. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  40142. // IAnimatable
  40143. _this.animations = [];
  40144. // Values
  40145. _this._bloomEnabled = false;
  40146. _this._fxaaEnabled = false;
  40147. _this._imageProcessingEnabled = true;
  40148. _this._bloomScale = 0.6;
  40149. /**
  40150. * Specifies the size of the bloom blur kernel, relative to the final output size
  40151. */
  40152. _this.bloomKernel = 64;
  40153. /**
  40154. * Specifies the weight of the bloom in the final rendering
  40155. */
  40156. _this._bloomWeight = 0.15;
  40157. _this._cameras = cameras || [];
  40158. // Initialize
  40159. _this._scene = scene;
  40160. var caps = _this._scene.getEngine().getCaps();
  40161. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  40162. // Misc
  40163. if (_this._hdr) {
  40164. if (caps.textureHalfFloatRender) {
  40165. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  40166. }
  40167. else if (caps.textureFloatRender) {
  40168. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  40169. }
  40170. }
  40171. else {
  40172. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  40173. }
  40174. // Attach
  40175. scene.postProcessRenderPipelineManager.addPipeline(_this);
  40176. _this._buildPipeline();
  40177. return _this;
  40178. }
  40179. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  40180. get: function () {
  40181. return this._bloomWeight;
  40182. },
  40183. set: function (value) {
  40184. if (this._bloomWeight === value) {
  40185. return;
  40186. }
  40187. this._bloomWeight = value;
  40188. if (this._hdr && this.copyBack) {
  40189. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  40190. }
  40191. },
  40192. enumerable: true,
  40193. configurable: true
  40194. });
  40195. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  40196. get: function () {
  40197. return this._bloomScale;
  40198. },
  40199. set: function (value) {
  40200. if (this._bloomScale === value) {
  40201. return;
  40202. }
  40203. this._bloomScale = value;
  40204. this._buildPipeline();
  40205. },
  40206. enumerable: true,
  40207. configurable: true
  40208. });
  40209. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  40210. get: function () {
  40211. return this._bloomEnabled;
  40212. },
  40213. set: function (enabled) {
  40214. if (this._bloomEnabled === enabled) {
  40215. return;
  40216. }
  40217. this._bloomEnabled = enabled;
  40218. this._buildPipeline();
  40219. },
  40220. enumerable: true,
  40221. configurable: true
  40222. });
  40223. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  40224. get: function () {
  40225. return this._fxaaEnabled;
  40226. },
  40227. set: function (enabled) {
  40228. if (this._fxaaEnabled === enabled) {
  40229. return;
  40230. }
  40231. this._fxaaEnabled = enabled;
  40232. this._buildPipeline();
  40233. },
  40234. enumerable: true,
  40235. configurable: true
  40236. });
  40237. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  40238. get: function () {
  40239. return this._imageProcessingEnabled;
  40240. },
  40241. set: function (enabled) {
  40242. if (this._imageProcessingEnabled === enabled) {
  40243. return;
  40244. }
  40245. this._imageProcessingEnabled = enabled;
  40246. this._buildPipeline();
  40247. },
  40248. enumerable: true,
  40249. configurable: true
  40250. });
  40251. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  40252. var _this = this;
  40253. var engine = this._scene.getEngine();
  40254. this._disposePostProcesses();
  40255. this._reset();
  40256. if (this.bloomEnabled) {
  40257. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40258. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  40259. if (!this._hdr) {
  40260. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40261. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  40262. this.highlights.autoClear = false;
  40263. this.highlights.alwaysForcePOT = true;
  40264. }
  40265. 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);
  40266. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  40267. this.blurX.alwaysForcePOT = true;
  40268. this.blurX.autoClear = false;
  40269. this.blurX.onActivateObservable.add(function () {
  40270. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  40271. _this.blurX.kernel = _this.bloomKernel * dw;
  40272. });
  40273. 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);
  40274. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  40275. this.blurY.alwaysForcePOT = true;
  40276. this.blurY.autoClear = false;
  40277. this.blurY.onActivateObservable.add(function () {
  40278. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  40279. _this.blurY.kernel = _this.bloomKernel * dh;
  40280. });
  40281. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40282. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  40283. this.copyBack.alwaysForcePOT = true;
  40284. if (this._hdr) {
  40285. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  40286. var w = this.bloomWeight;
  40287. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  40288. }
  40289. else {
  40290. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  40291. }
  40292. this.copyBack.autoClear = false;
  40293. }
  40294. if (this._imageProcessingEnabled) {
  40295. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40296. if (this._hdr) {
  40297. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  40298. }
  40299. }
  40300. if (this.fxaaEnabled) {
  40301. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40302. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  40303. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40304. }
  40305. else {
  40306. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40307. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  40308. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40309. }
  40310. if (this.bloomEnabled) {
  40311. if (this._hdr) {
  40312. this.copyBack.shareOutputWith(this.blurX);
  40313. if (this.imageProcessing) {
  40314. this.imageProcessing.shareOutputWith(this.pass);
  40315. this.imageProcessing.autoClear = false;
  40316. }
  40317. else if (this.fxaa) {
  40318. this.fxaa.shareOutputWith(this.pass);
  40319. }
  40320. else {
  40321. this.finalMerge.shareOutputWith(this.pass);
  40322. }
  40323. }
  40324. else {
  40325. if (this.fxaa) {
  40326. this.fxaa.shareOutputWith(this.pass);
  40327. }
  40328. else {
  40329. this.finalMerge.shareOutputWith(this.pass);
  40330. }
  40331. }
  40332. }
  40333. if (this._cameras !== null) {
  40334. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  40335. }
  40336. };
  40337. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  40338. for (var i = 0; i < this._cameras.length; i++) {
  40339. var camera = this._cameras[i];
  40340. if (this.pass) {
  40341. this.pass.dispose(camera);
  40342. }
  40343. if (this.highlights) {
  40344. this.highlights.dispose(camera);
  40345. }
  40346. if (this.blurX) {
  40347. this.blurX.dispose(camera);
  40348. }
  40349. if (this.blurY) {
  40350. this.blurY.dispose(camera);
  40351. }
  40352. if (this.copyBack) {
  40353. this.copyBack.dispose(camera);
  40354. }
  40355. if (this.imageProcessing) {
  40356. this.imageProcessing.dispose(camera);
  40357. }
  40358. if (this.fxaa) {
  40359. this.fxaa.dispose(camera);
  40360. }
  40361. if (this.finalMerge) {
  40362. this.finalMerge.dispose(camera);
  40363. }
  40364. }
  40365. this.pass = null;
  40366. this.highlights = null;
  40367. this.blurX = null;
  40368. this.blurY = null;
  40369. this.copyBack = null;
  40370. this.imageProcessing = null;
  40371. this.fxaa = null;
  40372. this.finalMerge = null;
  40373. };
  40374. // Dispose
  40375. DefaultRenderingPipeline.prototype.dispose = function () {
  40376. this._disposePostProcesses();
  40377. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  40378. _super.prototype.dispose.call(this);
  40379. };
  40380. // Serialize rendering pipeline
  40381. DefaultRenderingPipeline.prototype.serialize = function () {
  40382. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40383. serializationObject.customType = "DefaultRenderingPipeline";
  40384. return serializationObject;
  40385. };
  40386. // Parse serialized pipeline
  40387. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  40388. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  40389. };
  40390. return DefaultRenderingPipeline;
  40391. }(BABYLON.PostProcessRenderPipeline));
  40392. __decorate([
  40393. BABYLON.serialize()
  40394. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  40395. __decorate([
  40396. BABYLON.serialize()
  40397. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  40398. __decorate([
  40399. BABYLON.serialize()
  40400. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  40401. __decorate([
  40402. BABYLON.serialize()
  40403. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  40404. __decorate([
  40405. BABYLON.serialize()
  40406. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  40407. __decorate([
  40408. BABYLON.serialize()
  40409. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  40410. __decorate([
  40411. BABYLON.serialize()
  40412. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  40413. __decorate([
  40414. BABYLON.serialize()
  40415. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  40416. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  40417. })(BABYLON || (BABYLON = {}));
  40418. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  40419. var BABYLON;
  40420. (function (BABYLON) {
  40421. /**
  40422. * This groups together the common properties used for image processing either in direct forward pass
  40423. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40424. * or not.
  40425. */
  40426. var ImageProcessingConfiguration = (function () {
  40427. function ImageProcessingConfiguration() {
  40428. /**
  40429. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40430. */
  40431. this.colorCurves = new BABYLON.ColorCurves();
  40432. this._colorCurvesEnabled = false;
  40433. this._colorGradingEnabled = false;
  40434. this._colorGradingWithGreenDepth = false;
  40435. this._colorGradingBGR = false;
  40436. this._exposure = 1.0;
  40437. this._toneMappingEnabled = false;
  40438. this._contrast = 1.0;
  40439. /**
  40440. * Vignette stretch size.
  40441. */
  40442. this.vignetteStretch = 0;
  40443. /**
  40444. * Vignette centre X Offset.
  40445. */
  40446. this.vignetteCentreX = 0;
  40447. /**
  40448. * Vignette centre Y Offset.
  40449. */
  40450. this.vignetteCentreY = 0;
  40451. /**
  40452. * Vignette weight or intensity of the vignette effect.
  40453. */
  40454. this.vignetteWeight = 1.5;
  40455. /**
  40456. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40457. * if vignetteEnabled is set to true.
  40458. */
  40459. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40460. /**
  40461. * Camera field of view used by the Vignette effect.
  40462. */
  40463. this.vignetteCameraFov = 0.5;
  40464. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40465. this._vignetteEnabled = false;
  40466. this._applyByPostProcess = false;
  40467. /**
  40468. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40469. * @type {BABYLON.Observable}
  40470. */
  40471. this.onUpdateParameters = new BABYLON.Observable();
  40472. }
  40473. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40474. /**
  40475. * Gets wether the color curves effect is enabled.
  40476. */
  40477. get: function () {
  40478. return this._colorCurvesEnabled;
  40479. },
  40480. /**
  40481. * Sets wether the color curves effect is enabled.
  40482. */
  40483. set: function (value) {
  40484. if (this._colorCurvesEnabled === value) {
  40485. return;
  40486. }
  40487. this._colorCurvesEnabled = value;
  40488. this._updateParameters();
  40489. },
  40490. enumerable: true,
  40491. configurable: true
  40492. });
  40493. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40494. /**
  40495. * Gets wether the color grading effect is enabled.
  40496. */
  40497. get: function () {
  40498. return this._colorGradingEnabled;
  40499. },
  40500. /**
  40501. * Sets wether the color grading effect is enabled.
  40502. */
  40503. set: function (value) {
  40504. if (this._colorGradingEnabled === value) {
  40505. return;
  40506. }
  40507. this._colorGradingEnabled = value;
  40508. this._updateParameters();
  40509. },
  40510. enumerable: true,
  40511. configurable: true
  40512. });
  40513. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40514. /**
  40515. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40516. */
  40517. get: function () {
  40518. return this._colorGradingWithGreenDepth;
  40519. },
  40520. /**
  40521. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40522. */
  40523. set: function (value) {
  40524. if (this._colorGradingWithGreenDepth === value) {
  40525. return;
  40526. }
  40527. this._colorGradingWithGreenDepth = value;
  40528. this._updateParameters();
  40529. },
  40530. enumerable: true,
  40531. configurable: true
  40532. });
  40533. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40534. /**
  40535. * Gets wether the color grading texture contains BGR values.
  40536. */
  40537. get: function () {
  40538. return this._colorGradingBGR;
  40539. },
  40540. /**
  40541. * Sets wether the color grading texture contains BGR values.
  40542. */
  40543. set: function (value) {
  40544. if (this._colorGradingBGR === value) {
  40545. return;
  40546. }
  40547. this._colorGradingBGR = value;
  40548. this._updateParameters();
  40549. },
  40550. enumerable: true,
  40551. configurable: true
  40552. });
  40553. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40554. /**
  40555. * Gets the Exposure used in the effect.
  40556. */
  40557. get: function () {
  40558. return this._exposure;
  40559. },
  40560. /**
  40561. * Sets the Exposure used in the effect.
  40562. */
  40563. set: function (value) {
  40564. if (this._exposure === value) {
  40565. return;
  40566. }
  40567. this._exposure = value;
  40568. this._updateParameters();
  40569. },
  40570. enumerable: true,
  40571. configurable: true
  40572. });
  40573. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40574. /**
  40575. * Gets wether the tone mapping effect is enabled.
  40576. */
  40577. get: function () {
  40578. return this._toneMappingEnabled;
  40579. },
  40580. /**
  40581. * Sets wether the tone mapping effect is enabled.
  40582. */
  40583. set: function (value) {
  40584. if (this._toneMappingEnabled === value) {
  40585. return;
  40586. }
  40587. this._toneMappingEnabled = value;
  40588. this._updateParameters();
  40589. },
  40590. enumerable: true,
  40591. configurable: true
  40592. });
  40593. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40594. /**
  40595. * Gets the contrast used in the effect.
  40596. */
  40597. get: function () {
  40598. return this._contrast;
  40599. },
  40600. /**
  40601. * Sets the contrast used in the effect.
  40602. */
  40603. set: function (value) {
  40604. if (this._contrast === value) {
  40605. return;
  40606. }
  40607. this._contrast = value;
  40608. this._updateParameters();
  40609. },
  40610. enumerable: true,
  40611. configurable: true
  40612. });
  40613. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40614. /**
  40615. * Gets the vignette blend mode allowing different kind of effect.
  40616. */
  40617. get: function () {
  40618. return this._vignetteBlendMode;
  40619. },
  40620. /**
  40621. * Sets the vignette blend mode allowing different kind of effect.
  40622. */
  40623. set: function (value) {
  40624. if (this._vignetteBlendMode === value) {
  40625. return;
  40626. }
  40627. this._vignetteBlendMode = value;
  40628. this._updateParameters();
  40629. },
  40630. enumerable: true,
  40631. configurable: true
  40632. });
  40633. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40634. /**
  40635. * Gets wether the vignette effect is enabled.
  40636. */
  40637. get: function () {
  40638. return this._vignetteEnabled;
  40639. },
  40640. /**
  40641. * Sets wether the vignette effect is enabled.
  40642. */
  40643. set: function (value) {
  40644. if (this._vignetteEnabled === value) {
  40645. return;
  40646. }
  40647. this._vignetteEnabled = value;
  40648. this._updateParameters();
  40649. },
  40650. enumerable: true,
  40651. configurable: true
  40652. });
  40653. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40654. /**
  40655. * Gets wether the image processing is applied through a post process or not.
  40656. */
  40657. get: function () {
  40658. return this._applyByPostProcess;
  40659. },
  40660. /**
  40661. * Sets wether the image processing is applied through a post process or not.
  40662. */
  40663. set: function (value) {
  40664. if (this._applyByPostProcess === value) {
  40665. return;
  40666. }
  40667. this._applyByPostProcess = value;
  40668. this._updateParameters();
  40669. },
  40670. enumerable: true,
  40671. configurable: true
  40672. });
  40673. /**
  40674. * Method called each time the image processing information changes requires to recompile the effect.
  40675. */
  40676. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40677. this.onUpdateParameters.notifyObservers(this);
  40678. };
  40679. /**
  40680. * Prepare the list of uniforms associated with the Image Processing effects.
  40681. * @param uniformsList The list of uniforms used in the effect
  40682. * @param defines the list of defines currently in use
  40683. */
  40684. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40685. if (defines.EXPOSURE) {
  40686. uniforms.push("exposureLinear");
  40687. }
  40688. if (defines.CONTRAST) {
  40689. uniforms.push("contrast");
  40690. }
  40691. if (defines.COLORGRADING) {
  40692. uniforms.push("colorTransformSettings");
  40693. }
  40694. if (defines.VIGNETTE) {
  40695. uniforms.push("vInverseScreenSize");
  40696. uniforms.push("vignetteSettings1");
  40697. uniforms.push("vignetteSettings2");
  40698. }
  40699. if (defines.COLORCURVES) {
  40700. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40701. }
  40702. };
  40703. /**
  40704. * Prepare the list of samplers associated with the Image Processing effects.
  40705. * @param uniformsList The list of uniforms used in the effect
  40706. * @param defines the list of defines currently in use
  40707. */
  40708. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40709. if (defines.COLORGRADING) {
  40710. samplersList.push("txColorTransform");
  40711. }
  40712. };
  40713. /**
  40714. * Prepare the list of defines associated to the shader.
  40715. * @param defines the list of defines to complete
  40716. */
  40717. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  40718. defines.VIGNETTE = this.vignetteEnabled;
  40719. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40720. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40721. defines.TONEMAPPING = this.toneMappingEnabled;
  40722. defines.CONTRAST = (this.contrast !== 1.0);
  40723. defines.EXPOSURE = (this.exposure !== 1.0);
  40724. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40725. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40726. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40727. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40728. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40729. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40730. };
  40731. /**
  40732. * Returns true if all the image processing information are ready.
  40733. */
  40734. ImageProcessingConfiguration.prototype.isReady = function () {
  40735. // Color Grading texure can not be none blocking.
  40736. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40737. };
  40738. /**
  40739. * Binds the image processing to the shader.
  40740. * @param effect The effect to bind to
  40741. */
  40742. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40743. if (aspectRatio === void 0) { aspectRatio = 1; }
  40744. // Color Curves
  40745. if (this._colorCurvesEnabled) {
  40746. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40747. }
  40748. // Vignette
  40749. if (this._vignetteEnabled) {
  40750. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40751. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40752. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40753. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40754. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40755. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40756. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40757. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40758. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40759. var vignettePower = -2.0 * this.vignetteWeight;
  40760. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40761. }
  40762. // Exposure
  40763. effect.setFloat("exposureLinear", this.exposure);
  40764. // Contrast
  40765. effect.setFloat("contrast", this.contrast);
  40766. // Color transform settings
  40767. if (this.colorGradingTexture) {
  40768. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40769. var textureSize = this.colorGradingTexture.getSize().height;
  40770. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40771. 0.5 / textureSize, // textureOffset
  40772. textureSize, // textureSize
  40773. this.colorGradingTexture.level // weight
  40774. );
  40775. }
  40776. };
  40777. /**
  40778. * Clones the current image processing instance.
  40779. * @return The cloned image processing
  40780. */
  40781. ImageProcessingConfiguration.prototype.clone = function () {
  40782. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40783. };
  40784. /**
  40785. * Serializes the current image processing instance to a json representation.
  40786. * @return a JSON representation
  40787. */
  40788. ImageProcessingConfiguration.prototype.serialize = function () {
  40789. return BABYLON.SerializationHelper.Serialize(this);
  40790. };
  40791. /**
  40792. * Parses the image processing from a json representation.
  40793. * @param source the JSON source to parse
  40794. * @return The parsed image processing
  40795. */
  40796. ImageProcessingConfiguration.Parse = function (source) {
  40797. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40798. };
  40799. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40800. /**
  40801. * Used to apply the vignette as a mix with the pixel color.
  40802. */
  40803. get: function () {
  40804. return this._VIGNETTEMODE_MULTIPLY;
  40805. },
  40806. enumerable: true,
  40807. configurable: true
  40808. });
  40809. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40810. /**
  40811. * Used to apply the vignette as a replacement of the pixel color.
  40812. */
  40813. get: function () {
  40814. return this._VIGNETTEMODE_OPAQUE;
  40815. },
  40816. enumerable: true,
  40817. configurable: true
  40818. });
  40819. return ImageProcessingConfiguration;
  40820. }());
  40821. // Static constants associated to the image processing.
  40822. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40823. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40824. __decorate([
  40825. BABYLON.serializeAsColorCurves()
  40826. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40827. __decorate([
  40828. BABYLON.serialize()
  40829. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40830. __decorate([
  40831. BABYLON.serializeAsTexture()
  40832. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40833. __decorate([
  40834. BABYLON.serialize()
  40835. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40836. __decorate([
  40837. BABYLON.serialize()
  40838. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40839. __decorate([
  40840. BABYLON.serialize()
  40841. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40842. __decorate([
  40843. BABYLON.serialize()
  40844. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40845. __decorate([
  40846. BABYLON.serialize()
  40847. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40848. __decorate([
  40849. BABYLON.serialize()
  40850. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40851. __decorate([
  40852. BABYLON.serialize()
  40853. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40854. __decorate([
  40855. BABYLON.serialize()
  40856. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40857. __decorate([
  40858. BABYLON.serialize()
  40859. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40860. __decorate([
  40861. BABYLON.serialize()
  40862. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40863. __decorate([
  40864. BABYLON.serializeAsColor4()
  40865. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40866. __decorate([
  40867. BABYLON.serialize()
  40868. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40869. __decorate([
  40870. BABYLON.serialize()
  40871. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40872. __decorate([
  40873. BABYLON.serialize()
  40874. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40875. __decorate([
  40876. BABYLON.serialize()
  40877. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40878. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40879. })(BABYLON || (BABYLON = {}));
  40880. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40881. /// <reference path="babylon.mesh.ts" />
  40882. var BABYLON;
  40883. (function (BABYLON) {
  40884. var GroundMesh = (function (_super) {
  40885. __extends(GroundMesh, _super);
  40886. function GroundMesh(name, scene) {
  40887. var _this = _super.call(this, name, scene) || this;
  40888. _this.generateOctree = false;
  40889. _this._worldInverse = new BABYLON.Matrix();
  40890. return _this;
  40891. }
  40892. GroundMesh.prototype.getClassName = function () {
  40893. return "GroundMesh";
  40894. };
  40895. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40896. get: function () {
  40897. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40898. },
  40899. enumerable: true,
  40900. configurable: true
  40901. });
  40902. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40903. get: function () {
  40904. return this._subdivisionsX;
  40905. },
  40906. enumerable: true,
  40907. configurable: true
  40908. });
  40909. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40910. get: function () {
  40911. return this._subdivisionsY;
  40912. },
  40913. enumerable: true,
  40914. configurable: true
  40915. });
  40916. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40917. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40918. this._subdivisionsX = chunksCount;
  40919. this._subdivisionsY = chunksCount;
  40920. this.subdivide(chunksCount);
  40921. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40922. };
  40923. /**
  40924. * Returns a height (y) value in the Worl system :
  40925. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40926. * Returns the ground y position if (x, z) are outside the ground surface.
  40927. */
  40928. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40929. var world = this.getWorldMatrix();
  40930. var invMat = BABYLON.Tmp.Matrix[5];
  40931. world.invertToRef(invMat);
  40932. var tmpVect = BABYLON.Tmp.Vector3[8];
  40933. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40934. x = tmpVect.x;
  40935. z = tmpVect.z;
  40936. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40937. return this.position.y;
  40938. }
  40939. if (!this._heightQuads || this._heightQuads.length == 0) {
  40940. this._initHeightQuads();
  40941. this._computeHeightQuads();
  40942. }
  40943. var facet = this._getFacetAt(x, z);
  40944. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40945. // return y in the World system
  40946. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40947. return tmpVect.y;
  40948. };
  40949. /**
  40950. * Returns a normalized vector (Vector3) orthogonal to the ground
  40951. * at the ground coordinates (x, z) expressed in the World system.
  40952. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40953. */
  40954. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40955. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40956. this.getNormalAtCoordinatesToRef(x, z, normal);
  40957. return normal;
  40958. };
  40959. /**
  40960. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40961. * at the ground coordinates (x, z) expressed in the World system.
  40962. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40963. * Returns the GroundMesh.
  40964. */
  40965. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40966. var world = this.getWorldMatrix();
  40967. var tmpMat = BABYLON.Tmp.Matrix[5];
  40968. world.invertToRef(tmpMat);
  40969. var tmpVect = BABYLON.Tmp.Vector3[8];
  40970. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40971. x = tmpVect.x;
  40972. z = tmpVect.z;
  40973. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40974. return this;
  40975. }
  40976. if (!this._heightQuads || this._heightQuads.length == 0) {
  40977. this._initHeightQuads();
  40978. this._computeHeightQuads();
  40979. }
  40980. var facet = this._getFacetAt(x, z);
  40981. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40982. return this;
  40983. };
  40984. /**
  40985. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40986. * if the ground has been updated.
  40987. * This can be used in the render loop.
  40988. * Returns the GroundMesh.
  40989. */
  40990. GroundMesh.prototype.updateCoordinateHeights = function () {
  40991. if (!this._heightQuads || this._heightQuads.length == 0) {
  40992. this._initHeightQuads();
  40993. }
  40994. this._computeHeightQuads();
  40995. return this;
  40996. };
  40997. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40998. GroundMesh.prototype._getFacetAt = function (x, z) {
  40999. // retrieve col and row from x, z coordinates in the ground local system
  41000. var subdivisionsX = this._subdivisionsX;
  41001. var subdivisionsY = this._subdivisionsY;
  41002. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41003. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41004. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41005. var facet;
  41006. if (z < quad.slope.x * x + quad.slope.y) {
  41007. facet = quad.facet1;
  41008. }
  41009. else {
  41010. facet = quad.facet2;
  41011. }
  41012. return facet;
  41013. };
  41014. // Creates and populates the heightMap array with "facet" elements :
  41015. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41016. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41017. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41018. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41019. // Returns the GroundMesh.
  41020. GroundMesh.prototype._initHeightQuads = function () {
  41021. var subdivisionsX = this._subdivisionsX;
  41022. var subdivisionsY = this._subdivisionsY;
  41023. this._heightQuads = new Array();
  41024. for (var row = 0; row < subdivisionsY; row++) {
  41025. for (var col = 0; col < subdivisionsX; col++) {
  41026. 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) };
  41027. this._heightQuads[row * subdivisionsX + col] = quad;
  41028. }
  41029. }
  41030. return this;
  41031. };
  41032. // Compute each quad element values and update the the heightMap array :
  41033. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41034. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41035. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41036. // Returns the GroundMesh.
  41037. GroundMesh.prototype._computeHeightQuads = function () {
  41038. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41039. var v1 = BABYLON.Tmp.Vector3[3];
  41040. var v2 = BABYLON.Tmp.Vector3[2];
  41041. var v3 = BABYLON.Tmp.Vector3[1];
  41042. var v4 = BABYLON.Tmp.Vector3[0];
  41043. var v1v2 = BABYLON.Tmp.Vector3[4];
  41044. var v1v3 = BABYLON.Tmp.Vector3[5];
  41045. var v1v4 = BABYLON.Tmp.Vector3[6];
  41046. var norm1 = BABYLON.Tmp.Vector3[7];
  41047. var norm2 = BABYLON.Tmp.Vector3[8];
  41048. var i = 0;
  41049. var j = 0;
  41050. var k = 0;
  41051. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41052. var h = 0;
  41053. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41054. var d2 = 0;
  41055. var subdivisionsX = this._subdivisionsX;
  41056. var subdivisionsY = this._subdivisionsY;
  41057. for (var row = 0; row < subdivisionsY; row++) {
  41058. for (var col = 0; col < subdivisionsX; col++) {
  41059. i = col * 3;
  41060. j = row * (subdivisionsX + 1) * 3;
  41061. k = (row + 1) * (subdivisionsX + 1) * 3;
  41062. v1.x = positions[j + i];
  41063. v1.y = positions[j + i + 1];
  41064. v1.z = positions[j + i + 2];
  41065. v2.x = positions[j + i + 3];
  41066. v2.y = positions[j + i + 4];
  41067. v2.z = positions[j + i + 5];
  41068. v3.x = positions[k + i];
  41069. v3.y = positions[k + i + 1];
  41070. v3.z = positions[k + i + 2];
  41071. v4.x = positions[k + i + 3];
  41072. v4.y = positions[k + i + 4];
  41073. v4.z = positions[k + i + 5];
  41074. // 2D slope V1V4
  41075. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41076. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41077. // facet equations :
  41078. // we compute each facet normal vector
  41079. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41080. // we compute the value d by applying the equation to v1 which belongs to the plane
  41081. // then we store the facet equation in a Vector4
  41082. v2.subtractToRef(v1, v1v2);
  41083. v3.subtractToRef(v1, v1v3);
  41084. v4.subtractToRef(v1, v1v4);
  41085. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41086. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41087. norm1.normalize();
  41088. norm2.normalize();
  41089. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41090. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41091. var quad = this._heightQuads[row * subdivisionsX + col];
  41092. quad.slope.copyFromFloats(cd, h);
  41093. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41094. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41095. }
  41096. }
  41097. return this;
  41098. };
  41099. GroundMesh.prototype.serialize = function (serializationObject) {
  41100. _super.prototype.serialize.call(this, serializationObject);
  41101. serializationObject.subdivisionsX = this._subdivisionsX;
  41102. serializationObject.subdivisionsY = this._subdivisionsY;
  41103. serializationObject.minX = this._minX;
  41104. serializationObject.maxX = this._maxX;
  41105. serializationObject.minZ = this._minZ;
  41106. serializationObject.maxZ = this._maxZ;
  41107. serializationObject.width = this._width;
  41108. serializationObject.height = this._height;
  41109. };
  41110. GroundMesh.Parse = function (parsedMesh, scene) {
  41111. var result = new GroundMesh(parsedMesh.name, scene);
  41112. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41113. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41114. result._minX = parsedMesh.minX;
  41115. result._maxX = parsedMesh.maxX;
  41116. result._minZ = parsedMesh.minZ;
  41117. result._maxZ = parsedMesh.maxZ;
  41118. result._width = parsedMesh.width;
  41119. result._height = parsedMesh.height;
  41120. return result;
  41121. };
  41122. return GroundMesh;
  41123. }(BABYLON.Mesh));
  41124. BABYLON.GroundMesh = GroundMesh;
  41125. })(BABYLON || (BABYLON = {}));
  41126. //# sourceMappingURL=babylon.groundMesh.js.map
  41127. var BABYLON;
  41128. (function (BABYLON) {
  41129. /**
  41130. * Creates an instance based on a source mesh.
  41131. */
  41132. var InstancedMesh = (function (_super) {
  41133. __extends(InstancedMesh, _super);
  41134. function InstancedMesh(name, source) {
  41135. var _this = _super.call(this, name, source.getScene()) || this;
  41136. source.instances.push(_this);
  41137. _this._sourceMesh = source;
  41138. _this.position.copyFrom(source.position);
  41139. _this.rotation.copyFrom(source.rotation);
  41140. _this.scaling.copyFrom(source.scaling);
  41141. if (source.rotationQuaternion) {
  41142. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41143. }
  41144. _this.infiniteDistance = source.infiniteDistance;
  41145. _this.setPivotMatrix(source.getPivotMatrix());
  41146. _this.refreshBoundingInfo();
  41147. _this._syncSubMeshes();
  41148. return _this;
  41149. }
  41150. /**
  41151. * Returns the string "InstancedMesh".
  41152. */
  41153. InstancedMesh.prototype.getClassName = function () {
  41154. return "InstancedMesh";
  41155. };
  41156. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41157. // Methods
  41158. get: function () {
  41159. return this._sourceMesh.receiveShadows;
  41160. },
  41161. enumerable: true,
  41162. configurable: true
  41163. });
  41164. Object.defineProperty(InstancedMesh.prototype, "material", {
  41165. get: function () {
  41166. return this._sourceMesh.material;
  41167. },
  41168. enumerable: true,
  41169. configurable: true
  41170. });
  41171. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  41172. get: function () {
  41173. return this._sourceMesh.visibility;
  41174. },
  41175. enumerable: true,
  41176. configurable: true
  41177. });
  41178. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  41179. get: function () {
  41180. return this._sourceMesh.skeleton;
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  41186. get: function () {
  41187. return this._sourceMesh.renderingGroupId;
  41188. },
  41189. enumerable: true,
  41190. configurable: true
  41191. });
  41192. /**
  41193. * Returns the total number of vertices (integer).
  41194. */
  41195. InstancedMesh.prototype.getTotalVertices = function () {
  41196. return this._sourceMesh.getTotalVertices();
  41197. };
  41198. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  41199. get: function () {
  41200. return this._sourceMesh;
  41201. },
  41202. enumerable: true,
  41203. configurable: true
  41204. });
  41205. /**
  41206. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  41207. */
  41208. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  41209. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  41210. };
  41211. /**
  41212. * Sets the vertex data of the mesh geometry for the requested `kind`.
  41213. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  41214. * The `data` are either a numeric array either a Float32Array.
  41215. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  41216. * 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).
  41217. * Note that a new underlying VertexBuffer object is created each call.
  41218. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  41219. *
  41220. * Possible `kind` values :
  41221. * - BABYLON.VertexBuffer.PositionKind
  41222. * - BABYLON.VertexBuffer.UVKind
  41223. * - BABYLON.VertexBuffer.UV2Kind
  41224. * - BABYLON.VertexBuffer.UV3Kind
  41225. * - BABYLON.VertexBuffer.UV4Kind
  41226. * - BABYLON.VertexBuffer.UV5Kind
  41227. * - BABYLON.VertexBuffer.UV6Kind
  41228. * - BABYLON.VertexBuffer.ColorKind
  41229. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41230. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41231. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41232. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41233. *
  41234. * Returns the Mesh.
  41235. */
  41236. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41237. if (this.sourceMesh) {
  41238. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  41239. }
  41240. return this.sourceMesh;
  41241. };
  41242. /**
  41243. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  41244. * If the mesh has no geometry, it is simply returned as it is.
  41245. * The `data` are either a numeric array either a Float32Array.
  41246. * No new underlying VertexBuffer object is created.
  41247. * 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.
  41248. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  41249. *
  41250. * Possible `kind` values :
  41251. * - BABYLON.VertexBuffer.PositionKind
  41252. * - BABYLON.VertexBuffer.UVKind
  41253. * - BABYLON.VertexBuffer.UV2Kind
  41254. * - BABYLON.VertexBuffer.UV3Kind
  41255. * - BABYLON.VertexBuffer.UV4Kind
  41256. * - BABYLON.VertexBuffer.UV5Kind
  41257. * - BABYLON.VertexBuffer.UV6Kind
  41258. * - BABYLON.VertexBuffer.ColorKind
  41259. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41260. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41261. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41262. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41263. *
  41264. * Returns the Mesh.
  41265. */
  41266. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  41267. if (this.sourceMesh) {
  41268. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  41269. }
  41270. return this.sourceMesh;
  41271. };
  41272. /**
  41273. * Sets the mesh indices.
  41274. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  41275. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  41276. * This method creates a new index buffer each call.
  41277. * Returns the Mesh.
  41278. */
  41279. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  41280. if (this.sourceMesh) {
  41281. this.sourceMesh.setIndices(indices, totalVertices);
  41282. }
  41283. return this.sourceMesh;
  41284. };
  41285. /**
  41286. * Boolean : True if the mesh owns the requested kind of data.
  41287. */
  41288. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  41289. return this._sourceMesh.isVerticesDataPresent(kind);
  41290. };
  41291. /**
  41292. * Returns an array of indices (IndicesArray).
  41293. */
  41294. InstancedMesh.prototype.getIndices = function () {
  41295. return this._sourceMesh.getIndices();
  41296. };
  41297. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  41298. get: function () {
  41299. return this._sourceMesh._positions;
  41300. },
  41301. enumerable: true,
  41302. configurable: true
  41303. });
  41304. /**
  41305. * Sets a new updated BoundingInfo to the mesh.
  41306. * Returns the mesh.
  41307. */
  41308. InstancedMesh.prototype.refreshBoundingInfo = function () {
  41309. var meshBB = this._sourceMesh.getBoundingInfo();
  41310. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  41311. this._updateBoundingInfo();
  41312. return this;
  41313. };
  41314. InstancedMesh.prototype._preActivate = function () {
  41315. if (this._currentLOD) {
  41316. this._currentLOD._preActivate();
  41317. }
  41318. return this;
  41319. };
  41320. InstancedMesh.prototype._activate = function (renderId) {
  41321. if (this._currentLOD) {
  41322. this._currentLOD._registerInstanceForRenderId(this, renderId);
  41323. }
  41324. return this;
  41325. };
  41326. /**
  41327. * Returns the current associated LOD AbstractMesh.
  41328. */
  41329. InstancedMesh.prototype.getLOD = function (camera) {
  41330. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  41331. if (this._currentLOD === this.sourceMesh) {
  41332. return this;
  41333. }
  41334. return this._currentLOD;
  41335. };
  41336. InstancedMesh.prototype._syncSubMeshes = function () {
  41337. this.releaseSubMeshes();
  41338. if (this._sourceMesh.subMeshes) {
  41339. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41340. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41341. }
  41342. }
  41343. return this;
  41344. };
  41345. InstancedMesh.prototype._generatePointsArray = function () {
  41346. return this._sourceMesh._generatePointsArray();
  41347. };
  41348. /**
  41349. * Creates a new InstancedMesh from the current mesh.
  41350. * - name (string) : the cloned mesh name
  41351. * - newParent (optional Node) : the optional Node to parent the clone to.
  41352. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41353. *
  41354. * Returns the clone.
  41355. */
  41356. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41357. var result = this._sourceMesh.createInstance(name);
  41358. // Deep copy
  41359. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41360. // Bounding info
  41361. this.refreshBoundingInfo();
  41362. // Parent
  41363. if (newParent) {
  41364. result.parent = newParent;
  41365. }
  41366. if (!doNotCloneChildren) {
  41367. // Children
  41368. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41369. var mesh = this.getScene().meshes[index];
  41370. if (mesh.parent === this) {
  41371. mesh.clone(mesh.name, result);
  41372. }
  41373. }
  41374. }
  41375. result.computeWorldMatrix(true);
  41376. return result;
  41377. };
  41378. /**
  41379. * Disposes the InstancedMesh.
  41380. * Returns nothing.
  41381. */
  41382. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41383. // Remove from mesh
  41384. var index = this._sourceMesh.instances.indexOf(this);
  41385. this._sourceMesh.instances.splice(index, 1);
  41386. _super.prototype.dispose.call(this, doNotRecurse);
  41387. };
  41388. return InstancedMesh;
  41389. }(BABYLON.AbstractMesh));
  41390. BABYLON.InstancedMesh = InstancedMesh;
  41391. })(BABYLON || (BABYLON = {}));
  41392. //# sourceMappingURL=babylon.instancedMesh.js.map
  41393. /// <reference path="babylon.mesh.ts" />
  41394. var BABYLON;
  41395. (function (BABYLON) {
  41396. var LinesMesh = (function (_super) {
  41397. __extends(LinesMesh, _super);
  41398. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41399. if (parent === void 0) { parent = null; }
  41400. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41401. _this.useVertexColor = useVertexColor;
  41402. _this.color = new BABYLON.Color3(1, 1, 1);
  41403. _this.alpha = 1;
  41404. if (source) {
  41405. _this.color = source.color.clone();
  41406. _this.alpha = source.alpha;
  41407. _this.useVertexColor = source.useVertexColor;
  41408. }
  41409. _this._intersectionThreshold = 0.1;
  41410. var options = {
  41411. attributes: [BABYLON.VertexBuffer.PositionKind],
  41412. uniforms: ["world", "viewProjection"],
  41413. needAlphaBlending: false,
  41414. };
  41415. if (!useVertexColor) {
  41416. options.uniforms.push("color");
  41417. options.needAlphaBlending = true;
  41418. }
  41419. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41420. return _this;
  41421. }
  41422. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41423. /**
  41424. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41425. * This margin is expressed in world space coordinates, so its value may vary.
  41426. * Default value is 0.1
  41427. * @returns the intersection Threshold value.
  41428. */
  41429. get: function () {
  41430. return this._intersectionThreshold;
  41431. },
  41432. /**
  41433. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41434. * This margin is expressed in world space coordinates, so its value may vary.
  41435. * @param value the new threshold to apply
  41436. */
  41437. set: function (value) {
  41438. if (this._intersectionThreshold === value) {
  41439. return;
  41440. }
  41441. this._intersectionThreshold = value;
  41442. if (this.geometry) {
  41443. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41444. }
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. /**
  41450. * Returns the string "LineMesh"
  41451. */
  41452. LinesMesh.prototype.getClassName = function () {
  41453. return "LinesMesh";
  41454. };
  41455. Object.defineProperty(LinesMesh.prototype, "material", {
  41456. get: function () {
  41457. return this._colorShader;
  41458. },
  41459. enumerable: true,
  41460. configurable: true
  41461. });
  41462. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41463. get: function () {
  41464. return false;
  41465. },
  41466. enumerable: true,
  41467. configurable: true
  41468. });
  41469. LinesMesh.prototype.createInstance = function (name) {
  41470. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41471. return null;
  41472. };
  41473. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41474. // VBOs
  41475. this._geometry._bind(this._colorShader.getEffect());
  41476. // Color
  41477. if (!this.useVertexColor) {
  41478. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41479. }
  41480. return this;
  41481. };
  41482. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41483. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41484. return this;
  41485. }
  41486. var engine = this.getScene().getEngine();
  41487. // Draw order
  41488. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41489. return this;
  41490. };
  41491. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41492. this._colorShader.dispose();
  41493. _super.prototype.dispose.call(this, doNotRecurse);
  41494. };
  41495. /**
  41496. * Returns a new LineMesh object cloned from the current one.
  41497. */
  41498. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41499. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41500. };
  41501. return LinesMesh;
  41502. }(BABYLON.Mesh));
  41503. BABYLON.LinesMesh = LinesMesh;
  41504. })(BABYLON || (BABYLON = {}));
  41505. //# sourceMappingURL=babylon.linesMesh.js.map
  41506. var BABYLON;
  41507. (function (BABYLON) {
  41508. var StandardMaterialDefines = (function (_super) {
  41509. __extends(StandardMaterialDefines, _super);
  41510. function StandardMaterialDefines() {
  41511. var _this = _super.call(this) || this;
  41512. _this.DIFFUSE = false;
  41513. _this.AMBIENT = false;
  41514. _this.OPACITY = false;
  41515. _this.OPACITYRGB = false;
  41516. _this.REFLECTION = false;
  41517. _this.EMISSIVE = false;
  41518. _this.SPECULAR = false;
  41519. _this.BUMP = false;
  41520. _this.PARALLAX = false;
  41521. _this.PARALLAXOCCLUSION = false;
  41522. _this.SPECULAROVERALPHA = false;
  41523. _this.CLIPPLANE = false;
  41524. _this.ALPHATEST = false;
  41525. _this.ALPHAFROMDIFFUSE = false;
  41526. _this.POINTSIZE = false;
  41527. _this.FOG = false;
  41528. _this.SPECULARTERM = false;
  41529. _this.DIFFUSEFRESNEL = false;
  41530. _this.OPACITYFRESNEL = false;
  41531. _this.REFLECTIONFRESNEL = false;
  41532. _this.REFRACTIONFRESNEL = false;
  41533. _this.EMISSIVEFRESNEL = false;
  41534. _this.FRESNEL = false;
  41535. _this.NORMAL = false;
  41536. _this.UV1 = false;
  41537. _this.UV2 = false;
  41538. _this.VERTEXCOLOR = false;
  41539. _this.VERTEXALPHA = false;
  41540. _this.NUM_BONE_INFLUENCERS = 0;
  41541. _this.BonesPerMesh = 0;
  41542. _this.INSTANCES = false;
  41543. _this.GLOSSINESS = false;
  41544. _this.ROUGHNESS = false;
  41545. _this.EMISSIVEASILLUMINATION = false;
  41546. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41547. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41548. _this.LIGHTMAP = false;
  41549. _this.USELIGHTMAPASSHADOWMAP = false;
  41550. _this.REFLECTIONMAP_3D = false;
  41551. _this.REFLECTIONMAP_SPHERICAL = false;
  41552. _this.REFLECTIONMAP_PLANAR = false;
  41553. _this.REFLECTIONMAP_CUBIC = false;
  41554. _this.REFLECTIONMAP_PROJECTION = false;
  41555. _this.REFLECTIONMAP_SKYBOX = false;
  41556. _this.REFLECTIONMAP_EXPLICIT = false;
  41557. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41558. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41559. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41560. _this.INVERTCUBICMAP = false;
  41561. _this.LOGARITHMICDEPTH = false;
  41562. _this.REFRACTION = false;
  41563. _this.REFRACTIONMAP_3D = false;
  41564. _this.REFLECTIONOVERALPHA = false;
  41565. _this.INVERTNORMALMAPX = false;
  41566. _this.INVERTNORMALMAPY = false;
  41567. _this.TWOSIDEDLIGHTING = false;
  41568. _this.SHADOWFLOAT = false;
  41569. _this.MORPHTARGETS = false;
  41570. _this.MORPHTARGETS_NORMAL = false;
  41571. _this.MORPHTARGETS_TANGENT = false;
  41572. _this.NUM_MORPH_INFLUENCERS = 0;
  41573. _this.USERIGHTHANDEDSYSTEM = false;
  41574. _this.IMAGEPROCESSING = false;
  41575. _this.VIGNETTE = false;
  41576. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41577. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41578. _this.TONEMAPPING = false;
  41579. _this.CONTRAST = false;
  41580. _this.COLORCURVES = false;
  41581. _this.COLORGRADING = false;
  41582. _this.SAMPLER3DGREENDEPTH = false;
  41583. _this.SAMPLER3DBGRMAP = false;
  41584. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41585. _this.EXPOSURE = false;
  41586. _this.rebuild();
  41587. return _this;
  41588. }
  41589. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41590. var modes = [
  41591. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41592. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41593. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41594. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41595. ];
  41596. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41597. var mode = modes_1[_i];
  41598. this[mode] = (mode === modeToEnable);
  41599. }
  41600. };
  41601. return StandardMaterialDefines;
  41602. }(BABYLON.MaterialDefines));
  41603. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41604. var StandardMaterial = (function (_super) {
  41605. __extends(StandardMaterial, _super);
  41606. function StandardMaterial(name, scene) {
  41607. var _this = _super.call(this, name, scene) || this;
  41608. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41609. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41610. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41611. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41612. _this.specularPower = 64;
  41613. _this._useAlphaFromDiffuseTexture = false;
  41614. _this._useEmissiveAsIllumination = false;
  41615. _this._linkEmissiveWithDiffuse = false;
  41616. _this._useSpecularOverAlpha = false;
  41617. _this._useReflectionOverAlpha = false;
  41618. _this._disableLighting = false;
  41619. _this._useParallax = false;
  41620. _this._useParallaxOcclusion = false;
  41621. _this.parallaxScaleBias = 0.05;
  41622. _this._roughness = 0;
  41623. _this.indexOfRefraction = 0.98;
  41624. _this.invertRefractionY = true;
  41625. _this._useLightmapAsShadowmap = false;
  41626. _this._useReflectionFresnelFromSpecular = false;
  41627. _this._useGlossinessFromSpecularMapAlpha = false;
  41628. _this._maxSimultaneousLights = 4;
  41629. /**
  41630. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41631. */
  41632. _this._invertNormalMapX = false;
  41633. /**
  41634. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41635. */
  41636. _this._invertNormalMapY = false;
  41637. /**
  41638. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41639. */
  41640. _this._twoSidedLighting = false;
  41641. _this._renderTargets = new BABYLON.SmartArray(16);
  41642. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41643. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41644. // Setup the default processing configuration to the scene.
  41645. _this._attachImageProcessingConfiguration(null);
  41646. _this.getRenderTargetTextures = function () {
  41647. _this._renderTargets.reset();
  41648. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41649. _this._renderTargets.push(_this._reflectionTexture);
  41650. }
  41651. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41652. _this._renderTargets.push(_this._refractionTexture);
  41653. }
  41654. return _this._renderTargets;
  41655. };
  41656. return _this;
  41657. }
  41658. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41659. /**
  41660. * Gets the image processing configuration used either in this material.
  41661. */
  41662. get: function () {
  41663. return this._imageProcessingConfiguration;
  41664. },
  41665. /**
  41666. * Sets the Default image processing configuration used either in the this material.
  41667. *
  41668. * If sets to null, the scene one is in use.
  41669. */
  41670. set: function (value) {
  41671. this._attachImageProcessingConfiguration(value);
  41672. // Ensure the effect will be rebuilt.
  41673. this._markAllSubMeshesAsTexturesDirty();
  41674. },
  41675. enumerable: true,
  41676. configurable: true
  41677. });
  41678. /**
  41679. * Attaches a new image processing configuration to the Standard Material.
  41680. * @param configuration
  41681. */
  41682. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41683. var _this = this;
  41684. if (configuration === this._imageProcessingConfiguration) {
  41685. return;
  41686. }
  41687. // Detaches observer.
  41688. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41689. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41690. }
  41691. // Pick the scene configuration if needed.
  41692. if (!configuration) {
  41693. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41694. }
  41695. else {
  41696. this._imageProcessingConfiguration = configuration;
  41697. }
  41698. // Attaches observer.
  41699. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41700. _this._markAllSubMeshesAsImageProcessingDirty();
  41701. });
  41702. };
  41703. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41704. /**
  41705. * Gets wether the color curves effect is enabled.
  41706. */
  41707. get: function () {
  41708. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41709. },
  41710. /**
  41711. * Sets wether the color curves effect is enabled.
  41712. */
  41713. set: function (value) {
  41714. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41715. },
  41716. enumerable: true,
  41717. configurable: true
  41718. });
  41719. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41720. /**
  41721. * Gets wether the color grading effect is enabled.
  41722. */
  41723. get: function () {
  41724. return this.imageProcessingConfiguration.colorGradingEnabled;
  41725. },
  41726. /**
  41727. * Gets wether the color grading effect is enabled.
  41728. */
  41729. set: function (value) {
  41730. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41736. /**
  41737. * Gets wether tonemapping is enabled or not.
  41738. */
  41739. get: function () {
  41740. return this._imageProcessingConfiguration.toneMappingEnabled;
  41741. },
  41742. /**
  41743. * Sets wether tonemapping is enabled or not
  41744. */
  41745. set: function (value) {
  41746. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. ;
  41752. ;
  41753. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41754. /**
  41755. * The camera exposure used on this material.
  41756. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41757. * This corresponds to a photographic exposure.
  41758. */
  41759. get: function () {
  41760. return this._imageProcessingConfiguration.exposure;
  41761. },
  41762. /**
  41763. * The camera exposure used on this material.
  41764. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41765. * This corresponds to a photographic exposure.
  41766. */
  41767. set: function (value) {
  41768. this._imageProcessingConfiguration.exposure = value;
  41769. },
  41770. enumerable: true,
  41771. configurable: true
  41772. });
  41773. ;
  41774. ;
  41775. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41776. /**
  41777. * Gets The camera contrast used on this material.
  41778. */
  41779. get: function () {
  41780. return this._imageProcessingConfiguration.contrast;
  41781. },
  41782. /**
  41783. * Sets The camera contrast used on this material.
  41784. */
  41785. set: function (value) {
  41786. this._imageProcessingConfiguration.contrast = value;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41792. /**
  41793. * Gets the Color Grading 2D Lookup Texture.
  41794. */
  41795. get: function () {
  41796. return this._imageProcessingConfiguration.colorGradingTexture;
  41797. },
  41798. /**
  41799. * Sets the Color Grading 2D Lookup Texture.
  41800. */
  41801. set: function (value) {
  41802. this._imageProcessingConfiguration.colorGradingTexture = value;
  41803. },
  41804. enumerable: true,
  41805. configurable: true
  41806. });
  41807. StandardMaterial.prototype.getClassName = function () {
  41808. return "StandardMaterial";
  41809. };
  41810. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41811. get: function () {
  41812. return this._useLogarithmicDepth;
  41813. },
  41814. set: function (value) {
  41815. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41816. this._markAllSubMeshesAsMiscDirty();
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. StandardMaterial.prototype.needAlphaBlending = function () {
  41822. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41823. };
  41824. StandardMaterial.prototype.needAlphaTesting = function () {
  41825. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41826. };
  41827. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41828. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41829. };
  41830. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41831. return this._diffuseTexture;
  41832. };
  41833. /**
  41834. * Child classes can use it to update shaders
  41835. */
  41836. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41837. if (this.isFrozen) {
  41838. if (this._wasPreviouslyReady && subMesh.effect) {
  41839. return true;
  41840. }
  41841. }
  41842. if (!subMesh._materialDefines) {
  41843. subMesh._materialDefines = new StandardMaterialDefines();
  41844. }
  41845. var scene = this.getScene();
  41846. var defines = subMesh._materialDefines;
  41847. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41848. if (defines._renderId === scene.getRenderId()) {
  41849. return true;
  41850. }
  41851. }
  41852. var engine = scene.getEngine();
  41853. // Lights
  41854. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41855. // Textures
  41856. if (defines._areTexturesDirty) {
  41857. defines._needUVs = false;
  41858. if (scene.texturesEnabled) {
  41859. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41860. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41861. return false;
  41862. }
  41863. else {
  41864. defines._needUVs = true;
  41865. defines.DIFFUSE = true;
  41866. }
  41867. }
  41868. else {
  41869. defines.DIFFUSE = false;
  41870. }
  41871. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41872. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41873. return false;
  41874. }
  41875. else {
  41876. defines._needUVs = true;
  41877. defines.AMBIENT = true;
  41878. }
  41879. }
  41880. else {
  41881. defines.AMBIENT = false;
  41882. }
  41883. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41884. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41885. return false;
  41886. }
  41887. else {
  41888. defines._needUVs = true;
  41889. defines.OPACITY = true;
  41890. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41891. }
  41892. }
  41893. else {
  41894. defines.OPACITY = false;
  41895. }
  41896. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41897. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41898. return false;
  41899. }
  41900. else {
  41901. defines._needNormals = true;
  41902. defines.REFLECTION = true;
  41903. defines.ROUGHNESS = (this._roughness > 0);
  41904. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41905. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41906. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41907. switch (this._reflectionTexture.coordinatesMode) {
  41908. case BABYLON.Texture.CUBIC_MODE:
  41909. case BABYLON.Texture.INVCUBIC_MODE:
  41910. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41911. break;
  41912. case BABYLON.Texture.EXPLICIT_MODE:
  41913. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41914. break;
  41915. case BABYLON.Texture.PLANAR_MODE:
  41916. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41917. break;
  41918. case BABYLON.Texture.PROJECTION_MODE:
  41919. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41920. break;
  41921. case BABYLON.Texture.SKYBOX_MODE:
  41922. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41923. break;
  41924. case BABYLON.Texture.SPHERICAL_MODE:
  41925. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41926. break;
  41927. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41928. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41929. break;
  41930. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41931. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41932. break;
  41933. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41934. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41935. break;
  41936. }
  41937. }
  41938. }
  41939. else {
  41940. defines.REFLECTION = false;
  41941. }
  41942. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41943. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41944. return false;
  41945. }
  41946. else {
  41947. defines._needUVs = true;
  41948. defines.EMISSIVE = true;
  41949. }
  41950. }
  41951. else {
  41952. defines.EMISSIVE = false;
  41953. }
  41954. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41955. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41956. return false;
  41957. }
  41958. else {
  41959. defines._needUVs = true;
  41960. defines.LIGHTMAP = true;
  41961. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41962. }
  41963. }
  41964. else {
  41965. defines.LIGHTMAP = false;
  41966. }
  41967. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41968. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41969. return false;
  41970. }
  41971. else {
  41972. defines._needUVs = true;
  41973. defines.SPECULAR = true;
  41974. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41975. }
  41976. }
  41977. else {
  41978. defines.SPECULAR = false;
  41979. }
  41980. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41981. // Bump texure can not be not blocking.
  41982. if (!this._bumpTexture.isReady()) {
  41983. return false;
  41984. }
  41985. else {
  41986. defines._needUVs = true;
  41987. defines.BUMP = true;
  41988. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  41989. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  41990. defines.PARALLAX = this._useParallax;
  41991. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41992. }
  41993. }
  41994. else {
  41995. defines.BUMP = false;
  41996. }
  41997. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41998. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41999. return false;
  42000. }
  42001. else {
  42002. defines._needUVs = true;
  42003. defines.REFRACTION = true;
  42004. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42005. }
  42006. }
  42007. else {
  42008. defines.REFRACTION = false;
  42009. }
  42010. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42011. }
  42012. else {
  42013. defines.DIFFUSE = false;
  42014. defines.AMBIENT = false;
  42015. defines.OPACITY = false;
  42016. defines.REFLECTION = false;
  42017. defines.EMISSIVE = false;
  42018. defines.LIGHTMAP = false;
  42019. defines.BUMP = false;
  42020. defines.REFRACTION = false;
  42021. }
  42022. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42023. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42024. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42025. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42026. }
  42027. if (defines._areImageProcessingDirty) {
  42028. if (!this._imageProcessingConfiguration.isReady()) {
  42029. return false;
  42030. }
  42031. this._imageProcessingConfiguration.prepareDefines(defines);
  42032. }
  42033. if (defines._areFresnelDirty) {
  42034. if (StandardMaterial.FresnelEnabled) {
  42035. // Fresnel
  42036. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42037. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42038. this._reflectionFresnelParameters) {
  42039. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42040. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42041. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42042. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42043. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42044. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42045. defines._needNormals = true;
  42046. defines.FRESNEL = true;
  42047. }
  42048. }
  42049. else {
  42050. defines.FRESNEL = false;
  42051. }
  42052. }
  42053. // Misc.
  42054. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  42055. // Attribs
  42056. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42057. // Values that need to be evaluated on every frame
  42058. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42059. if (scene._mirroredCameraPosition && defines.BUMP) {
  42060. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  42061. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  42062. defines.markAsUnprocessed();
  42063. }
  42064. // Get correct effect
  42065. if (defines.isDirty) {
  42066. defines.markAsProcessed();
  42067. scene.resetCachedMaterial();
  42068. // Fallbacks
  42069. var fallbacks = new BABYLON.EffectFallbacks();
  42070. if (defines.REFLECTION) {
  42071. fallbacks.addFallback(0, "REFLECTION");
  42072. }
  42073. if (defines.SPECULAR) {
  42074. fallbacks.addFallback(0, "SPECULAR");
  42075. }
  42076. if (defines.BUMP) {
  42077. fallbacks.addFallback(0, "BUMP");
  42078. }
  42079. if (defines.PARALLAX) {
  42080. fallbacks.addFallback(1, "PARALLAX");
  42081. }
  42082. if (defines.PARALLAXOCCLUSION) {
  42083. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42084. }
  42085. if (defines.SPECULAROVERALPHA) {
  42086. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42087. }
  42088. if (defines.FOG) {
  42089. fallbacks.addFallback(1, "FOG");
  42090. }
  42091. if (defines.POINTSIZE) {
  42092. fallbacks.addFallback(0, "POINTSIZE");
  42093. }
  42094. if (defines.LOGARITHMICDEPTH) {
  42095. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42096. }
  42097. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42098. if (defines.SPECULARTERM) {
  42099. fallbacks.addFallback(0, "SPECULARTERM");
  42100. }
  42101. if (defines.DIFFUSEFRESNEL) {
  42102. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42103. }
  42104. if (defines.OPACITYFRESNEL) {
  42105. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42106. }
  42107. if (defines.REFLECTIONFRESNEL) {
  42108. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42109. }
  42110. if (defines.EMISSIVEFRESNEL) {
  42111. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42112. }
  42113. if (defines.FRESNEL) {
  42114. fallbacks.addFallback(4, "FRESNEL");
  42115. }
  42116. //Attributes
  42117. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42118. if (defines.NORMAL) {
  42119. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42120. }
  42121. if (defines.UV1) {
  42122. attribs.push(BABYLON.VertexBuffer.UVKind);
  42123. }
  42124. if (defines.UV2) {
  42125. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42126. }
  42127. if (defines.VERTEXCOLOR) {
  42128. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42129. }
  42130. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42131. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42132. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42133. var shaderName = "default";
  42134. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42135. "vFogInfos", "vFogColor", "pointSize",
  42136. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42137. "mBones",
  42138. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  42139. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42140. "logarithmicDepthConstant"
  42141. ];
  42142. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42143. var uniformBuffers = ["Material", "Scene"];
  42144. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42145. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42146. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42147. uniformsNames: uniforms,
  42148. uniformBuffersNames: uniformBuffers,
  42149. samplers: samplers,
  42150. defines: defines,
  42151. maxSimultaneousLights: this._maxSimultaneousLights
  42152. });
  42153. if (this.customShaderNameResolve) {
  42154. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42155. }
  42156. var join = defines.toString();
  42157. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42158. attributes: attribs,
  42159. uniformsNames: uniforms,
  42160. uniformBuffersNames: uniformBuffers,
  42161. samplers: samplers,
  42162. defines: join,
  42163. fallbacks: fallbacks,
  42164. onCompiled: this.onCompiled,
  42165. onError: this.onError,
  42166. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42167. }, engine), defines);
  42168. this.buildUniformLayout();
  42169. }
  42170. if (!subMesh.effect.isReady()) {
  42171. return false;
  42172. }
  42173. defines._renderId = scene.getRenderId();
  42174. this._wasPreviouslyReady = true;
  42175. return true;
  42176. };
  42177. StandardMaterial.prototype.buildUniformLayout = function () {
  42178. // Order is important !
  42179. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42180. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42181. this._uniformBuffer.addUniform("opacityParts", 4);
  42182. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42183. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42184. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42185. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42186. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42187. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42188. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42189. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42190. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42191. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42192. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42193. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42194. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42195. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42196. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42197. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42198. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42199. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42200. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42201. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42202. this._uniformBuffer.addUniform("specularMatrix", 16);
  42203. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42204. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42205. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42206. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42207. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42208. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42209. this._uniformBuffer.addUniform("pointSize", 1);
  42210. this._uniformBuffer.create();
  42211. };
  42212. StandardMaterial.prototype.unbind = function () {
  42213. if (this._activeEffect) {
  42214. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42215. this._activeEffect.setTexture("reflection2DSampler", null);
  42216. }
  42217. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42218. this._activeEffect.setTexture("refraction2DSampler", null);
  42219. }
  42220. }
  42221. _super.prototype.unbind.call(this);
  42222. };
  42223. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42224. var scene = this.getScene();
  42225. var defines = subMesh._materialDefines;
  42226. if (!defines) {
  42227. return;
  42228. }
  42229. var effect = subMesh.effect;
  42230. this._activeEffect = effect;
  42231. // Matrices
  42232. this.bindOnlyWorldMatrix(world);
  42233. // Bones
  42234. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42235. if (this._mustRebind(scene, effect, mesh.visibility)) {
  42236. this._uniformBuffer.bindToEffect(effect, "Material");
  42237. this.bindViewProjection(effect);
  42238. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42239. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42240. // Fresnel
  42241. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42242. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42243. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42244. }
  42245. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42246. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42247. }
  42248. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42249. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42250. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42251. }
  42252. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42253. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42254. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42255. }
  42256. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42257. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42258. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42259. }
  42260. }
  42261. // Textures
  42262. if (scene.texturesEnabled) {
  42263. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42264. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42265. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  42266. }
  42267. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42268. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42269. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  42270. }
  42271. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42272. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42273. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  42274. }
  42275. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42276. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42277. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42278. }
  42279. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42280. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42281. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  42282. }
  42283. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42284. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42285. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  42286. }
  42287. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42288. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42289. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  42290. }
  42291. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42292. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42293. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  42294. }
  42295. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42296. var depth = 1.0;
  42297. if (!this._refractionTexture.isCube) {
  42298. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42299. if (this._refractionTexture.depth) {
  42300. depth = this._refractionTexture.depth;
  42301. }
  42302. }
  42303. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42304. }
  42305. }
  42306. // Point size
  42307. if (this.pointsCloud) {
  42308. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42309. }
  42310. if (defines.SPECULARTERM) {
  42311. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42312. }
  42313. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42314. // Diffuse
  42315. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42316. }
  42317. // Textures
  42318. if (scene.texturesEnabled) {
  42319. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42320. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42321. }
  42322. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42323. effect.setTexture("ambientSampler", this._ambientTexture);
  42324. }
  42325. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42326. effect.setTexture("opacitySampler", this._opacityTexture);
  42327. }
  42328. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42329. if (this._reflectionTexture.isCube) {
  42330. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42331. }
  42332. else {
  42333. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42334. }
  42335. }
  42336. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42337. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42338. }
  42339. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42340. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42341. }
  42342. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42343. effect.setTexture("specularSampler", this._specularTexture);
  42344. }
  42345. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42346. effect.setTexture("bumpSampler", this._bumpTexture);
  42347. }
  42348. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42349. var depth = 1.0;
  42350. if (this._refractionTexture.isCube) {
  42351. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42352. }
  42353. else {
  42354. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42355. }
  42356. }
  42357. }
  42358. // Clip plane
  42359. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42360. // Colors
  42361. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42362. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  42363. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42364. }
  42365. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  42366. // Lights
  42367. if (scene.lightsEnabled && !this._disableLighting) {
  42368. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42369. }
  42370. // View
  42371. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42372. this.bindView(effect);
  42373. }
  42374. // Fog
  42375. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42376. // Morph targets
  42377. if (defines.NUM_MORPH_INFLUENCERS) {
  42378. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42379. }
  42380. // Log. depth
  42381. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42382. // image processing
  42383. this._imageProcessingConfiguration.bind(this._activeEffect);
  42384. }
  42385. this._uniformBuffer.update();
  42386. this._afterBind(mesh, this._activeEffect);
  42387. };
  42388. StandardMaterial.prototype.getAnimatables = function () {
  42389. var results = [];
  42390. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42391. results.push(this._diffuseTexture);
  42392. }
  42393. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42394. results.push(this._ambientTexture);
  42395. }
  42396. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42397. results.push(this._opacityTexture);
  42398. }
  42399. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42400. results.push(this._reflectionTexture);
  42401. }
  42402. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42403. results.push(this._emissiveTexture);
  42404. }
  42405. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42406. results.push(this._specularTexture);
  42407. }
  42408. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42409. results.push(this._bumpTexture);
  42410. }
  42411. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42412. results.push(this._lightmapTexture);
  42413. }
  42414. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42415. results.push(this._refractionTexture);
  42416. }
  42417. return results;
  42418. };
  42419. StandardMaterial.prototype.getActiveTextures = function () {
  42420. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42421. if (this._diffuseTexture) {
  42422. activeTextures.push(this._diffuseTexture);
  42423. }
  42424. if (this._ambientTexture) {
  42425. activeTextures.push(this._ambientTexture);
  42426. }
  42427. if (this._opacityTexture) {
  42428. activeTextures.push(this._opacityTexture);
  42429. }
  42430. if (this._reflectionTexture) {
  42431. activeTextures.push(this._reflectionTexture);
  42432. }
  42433. if (this._emissiveTexture) {
  42434. activeTextures.push(this._emissiveTexture);
  42435. }
  42436. if (this._specularTexture) {
  42437. activeTextures.push(this._specularTexture);
  42438. }
  42439. if (this._bumpTexture) {
  42440. activeTextures.push(this._bumpTexture);
  42441. }
  42442. if (this._lightmapTexture) {
  42443. activeTextures.push(this._lightmapTexture);
  42444. }
  42445. if (this._refractionTexture) {
  42446. activeTextures.push(this._refractionTexture);
  42447. }
  42448. return activeTextures;
  42449. };
  42450. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42451. if (forceDisposeTextures) {
  42452. if (this._diffuseTexture) {
  42453. this._diffuseTexture.dispose();
  42454. }
  42455. if (this._ambientTexture) {
  42456. this._ambientTexture.dispose();
  42457. }
  42458. if (this._opacityTexture) {
  42459. this._opacityTexture.dispose();
  42460. }
  42461. if (this._reflectionTexture) {
  42462. this._reflectionTexture.dispose();
  42463. }
  42464. if (this._emissiveTexture) {
  42465. this._emissiveTexture.dispose();
  42466. }
  42467. if (this._specularTexture) {
  42468. this._specularTexture.dispose();
  42469. }
  42470. if (this._bumpTexture) {
  42471. this._bumpTexture.dispose();
  42472. }
  42473. if (this._lightmapTexture) {
  42474. this._lightmapTexture.dispose();
  42475. }
  42476. if (this._refractionTexture) {
  42477. this._refractionTexture.dispose();
  42478. }
  42479. }
  42480. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42481. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42482. }
  42483. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42484. };
  42485. StandardMaterial.prototype.clone = function (name) {
  42486. var _this = this;
  42487. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42488. result.name = name;
  42489. result.id = name;
  42490. return result;
  42491. };
  42492. StandardMaterial.prototype.serialize = function () {
  42493. return BABYLON.SerializationHelper.Serialize(this);
  42494. };
  42495. // Statics
  42496. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42497. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42498. };
  42499. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42500. get: function () {
  42501. return StandardMaterial._DiffuseTextureEnabled;
  42502. },
  42503. set: function (value) {
  42504. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42505. return;
  42506. }
  42507. StandardMaterial._DiffuseTextureEnabled = value;
  42508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42509. },
  42510. enumerable: true,
  42511. configurable: true
  42512. });
  42513. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42514. get: function () {
  42515. return StandardMaterial._AmbientTextureEnabled;
  42516. },
  42517. set: function (value) {
  42518. if (StandardMaterial._AmbientTextureEnabled === value) {
  42519. return;
  42520. }
  42521. StandardMaterial._AmbientTextureEnabled = value;
  42522. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42523. },
  42524. enumerable: true,
  42525. configurable: true
  42526. });
  42527. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42528. get: function () {
  42529. return StandardMaterial._OpacityTextureEnabled;
  42530. },
  42531. set: function (value) {
  42532. if (StandardMaterial._OpacityTextureEnabled === value) {
  42533. return;
  42534. }
  42535. StandardMaterial._OpacityTextureEnabled = value;
  42536. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42537. },
  42538. enumerable: true,
  42539. configurable: true
  42540. });
  42541. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42542. get: function () {
  42543. return StandardMaterial._ReflectionTextureEnabled;
  42544. },
  42545. set: function (value) {
  42546. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42547. return;
  42548. }
  42549. StandardMaterial._ReflectionTextureEnabled = value;
  42550. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42551. },
  42552. enumerable: true,
  42553. configurable: true
  42554. });
  42555. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42556. get: function () {
  42557. return StandardMaterial._EmissiveTextureEnabled;
  42558. },
  42559. set: function (value) {
  42560. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42561. return;
  42562. }
  42563. StandardMaterial._EmissiveTextureEnabled = value;
  42564. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42565. },
  42566. enumerable: true,
  42567. configurable: true
  42568. });
  42569. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42570. get: function () {
  42571. return StandardMaterial._SpecularTextureEnabled;
  42572. },
  42573. set: function (value) {
  42574. if (StandardMaterial._SpecularTextureEnabled === value) {
  42575. return;
  42576. }
  42577. StandardMaterial._SpecularTextureEnabled = value;
  42578. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42579. },
  42580. enumerable: true,
  42581. configurable: true
  42582. });
  42583. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42584. get: function () {
  42585. return StandardMaterial._BumpTextureEnabled;
  42586. },
  42587. set: function (value) {
  42588. if (StandardMaterial._BumpTextureEnabled === value) {
  42589. return;
  42590. }
  42591. StandardMaterial._BumpTextureEnabled = value;
  42592. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42593. },
  42594. enumerable: true,
  42595. configurable: true
  42596. });
  42597. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42598. get: function () {
  42599. return StandardMaterial._LightmapTextureEnabled;
  42600. },
  42601. set: function (value) {
  42602. if (StandardMaterial._LightmapTextureEnabled === value) {
  42603. return;
  42604. }
  42605. StandardMaterial._LightmapTextureEnabled = value;
  42606. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42607. },
  42608. enumerable: true,
  42609. configurable: true
  42610. });
  42611. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42612. get: function () {
  42613. return StandardMaterial._RefractionTextureEnabled;
  42614. },
  42615. set: function (value) {
  42616. if (StandardMaterial._RefractionTextureEnabled === value) {
  42617. return;
  42618. }
  42619. StandardMaterial._RefractionTextureEnabled = value;
  42620. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42621. },
  42622. enumerable: true,
  42623. configurable: true
  42624. });
  42625. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42626. get: function () {
  42627. return StandardMaterial._ColorGradingTextureEnabled;
  42628. },
  42629. set: function (value) {
  42630. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42631. return;
  42632. }
  42633. StandardMaterial._ColorGradingTextureEnabled = value;
  42634. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42635. },
  42636. enumerable: true,
  42637. configurable: true
  42638. });
  42639. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42640. get: function () {
  42641. return StandardMaterial._FresnelEnabled;
  42642. },
  42643. set: function (value) {
  42644. if (StandardMaterial._FresnelEnabled === value) {
  42645. return;
  42646. }
  42647. StandardMaterial._FresnelEnabled = value;
  42648. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42649. },
  42650. enumerable: true,
  42651. configurable: true
  42652. });
  42653. return StandardMaterial;
  42654. }(BABYLON.PushMaterial));
  42655. // Flags used to enable or disable a type of texture for all Standard Materials
  42656. StandardMaterial._DiffuseTextureEnabled = true;
  42657. StandardMaterial._AmbientTextureEnabled = true;
  42658. StandardMaterial._OpacityTextureEnabled = true;
  42659. StandardMaterial._ReflectionTextureEnabled = true;
  42660. StandardMaterial._EmissiveTextureEnabled = true;
  42661. StandardMaterial._SpecularTextureEnabled = true;
  42662. StandardMaterial._BumpTextureEnabled = true;
  42663. StandardMaterial._LightmapTextureEnabled = true;
  42664. StandardMaterial._RefractionTextureEnabled = true;
  42665. StandardMaterial._ColorGradingTextureEnabled = true;
  42666. StandardMaterial._FresnelEnabled = true;
  42667. __decorate([
  42668. BABYLON.serializeAsTexture("diffuseTexture")
  42669. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42670. __decorate([
  42671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42672. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42673. __decorate([
  42674. BABYLON.serializeAsTexture("ambientTexture")
  42675. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42676. __decorate([
  42677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42678. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42679. __decorate([
  42680. BABYLON.serializeAsTexture("opacityTexture")
  42681. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42682. __decorate([
  42683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42684. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42685. __decorate([
  42686. BABYLON.serializeAsTexture("reflectionTexture")
  42687. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42688. __decorate([
  42689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42690. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42691. __decorate([
  42692. BABYLON.serializeAsTexture("emissiveTexture")
  42693. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42694. __decorate([
  42695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42696. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42697. __decorate([
  42698. BABYLON.serializeAsTexture("specularTexture")
  42699. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42700. __decorate([
  42701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42702. ], StandardMaterial.prototype, "specularTexture", void 0);
  42703. __decorate([
  42704. BABYLON.serializeAsTexture("bumpTexture")
  42705. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42706. __decorate([
  42707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42708. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42709. __decorate([
  42710. BABYLON.serializeAsTexture("lightmapTexture")
  42711. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42712. __decorate([
  42713. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42714. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42715. __decorate([
  42716. BABYLON.serializeAsTexture("refractionTexture")
  42717. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42718. __decorate([
  42719. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42720. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42721. __decorate([
  42722. BABYLON.serializeAsColor3("ambient")
  42723. ], StandardMaterial.prototype, "ambientColor", void 0);
  42724. __decorate([
  42725. BABYLON.serializeAsColor3("diffuse")
  42726. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42727. __decorate([
  42728. BABYLON.serializeAsColor3("specular")
  42729. ], StandardMaterial.prototype, "specularColor", void 0);
  42730. __decorate([
  42731. BABYLON.serializeAsColor3("emissive")
  42732. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42733. __decorate([
  42734. BABYLON.serialize()
  42735. ], StandardMaterial.prototype, "specularPower", void 0);
  42736. __decorate([
  42737. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42738. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42739. __decorate([
  42740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42741. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42742. __decorate([
  42743. BABYLON.serialize("useEmissiveAsIllumination")
  42744. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42745. __decorate([
  42746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42747. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42748. __decorate([
  42749. BABYLON.serialize("linkEmissiveWithDiffuse")
  42750. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42751. __decorate([
  42752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42753. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42754. __decorate([
  42755. BABYLON.serialize("useSpecularOverAlpha")
  42756. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42757. __decorate([
  42758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42759. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42760. __decorate([
  42761. BABYLON.serialize("useReflectionOverAlpha")
  42762. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42763. __decorate([
  42764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42765. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42766. __decorate([
  42767. BABYLON.serialize("disableLighting")
  42768. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42769. __decorate([
  42770. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42771. ], StandardMaterial.prototype, "disableLighting", void 0);
  42772. __decorate([
  42773. BABYLON.serialize("useParallax")
  42774. ], StandardMaterial.prototype, "_useParallax", void 0);
  42775. __decorate([
  42776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42777. ], StandardMaterial.prototype, "useParallax", void 0);
  42778. __decorate([
  42779. BABYLON.serialize("useParallaxOcclusion")
  42780. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42781. __decorate([
  42782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42783. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42784. __decorate([
  42785. BABYLON.serialize()
  42786. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42787. __decorate([
  42788. BABYLON.serialize("roughness")
  42789. ], StandardMaterial.prototype, "_roughness", void 0);
  42790. __decorate([
  42791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42792. ], StandardMaterial.prototype, "roughness", void 0);
  42793. __decorate([
  42794. BABYLON.serialize()
  42795. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42796. __decorate([
  42797. BABYLON.serialize()
  42798. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42799. __decorate([
  42800. BABYLON.serialize("useLightmapAsShadowmap")
  42801. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42802. __decorate([
  42803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42804. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42805. __decorate([
  42806. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42807. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42808. __decorate([
  42809. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42810. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42811. __decorate([
  42812. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42813. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42814. __decorate([
  42815. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42816. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42817. __decorate([
  42818. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42819. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42820. __decorate([
  42821. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42822. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42823. __decorate([
  42824. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42825. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42826. __decorate([
  42827. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42828. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42829. __decorate([
  42830. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42831. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42832. __decorate([
  42833. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42834. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42835. __decorate([
  42836. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42837. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42838. __decorate([
  42839. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42840. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42841. __decorate([
  42842. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42843. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42844. __decorate([
  42845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42846. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42847. __decorate([
  42848. BABYLON.serialize("maxSimultaneousLights")
  42849. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42850. __decorate([
  42851. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42852. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42853. __decorate([
  42854. BABYLON.serialize("invertNormalMapX")
  42855. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42856. __decorate([
  42857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42858. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42859. __decorate([
  42860. BABYLON.serialize("invertNormalMapY")
  42861. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42862. __decorate([
  42863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42864. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42865. __decorate([
  42866. BABYLON.serialize("twoSidedLighting")
  42867. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42868. __decorate([
  42869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42870. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42871. __decorate([
  42872. BABYLON.serialize()
  42873. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42874. BABYLON.StandardMaterial = StandardMaterial;
  42875. })(BABYLON || (BABYLON = {}));
  42876. //# sourceMappingURL=babylon.standardMaterial.js.map
  42877. var BABYLON;
  42878. (function (BABYLON) {
  42879. /**
  42880. * This class implement a typical dictionary using a string as key and the generic type T as value.
  42881. * The underlying implementation relies on an associative array to ensure the best performances.
  42882. * The value can be anything including 'null' but except 'undefined'
  42883. */
  42884. var StringDictionary = (function () {
  42885. function StringDictionary() {
  42886. this._count = 0;
  42887. this._data = {};
  42888. }
  42889. /**
  42890. * This will clear this dictionary and copy the content from the 'source' one.
  42891. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  42892. * @param source the dictionary to take the content from and copy to this dictionary
  42893. */
  42894. StringDictionary.prototype.copyFrom = function (source) {
  42895. var _this = this;
  42896. this.clear();
  42897. source.forEach(function (t, v) { return _this.add(t, v); });
  42898. };
  42899. /**
  42900. * Get a value based from its key
  42901. * @param key the given key to get the matching value from
  42902. * @return the value if found, otherwise undefined is returned
  42903. */
  42904. StringDictionary.prototype.get = function (key) {
  42905. var val = this._data[key];
  42906. if (val !== undefined) {
  42907. return val;
  42908. }
  42909. return undefined;
  42910. };
  42911. /**
  42912. * Get a value from its key or add it if it doesn't exist.
  42913. * This method will ensure you that a given key/data will be present in the dictionary.
  42914. * @param key the given key to get the matching value from
  42915. * @param factory the factory that will create the value if the key is not present in the dictionary.
  42916. * The factory will only be invoked if there's no data for the given key.
  42917. * @return the value corresponding to the key.
  42918. */
  42919. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  42920. var val = this.get(key);
  42921. if (val !== undefined) {
  42922. return val;
  42923. }
  42924. val = factory(key);
  42925. if (val) {
  42926. this.add(key, val);
  42927. }
  42928. return val;
  42929. };
  42930. /**
  42931. * Get a value from its key if present in the dictionary otherwise add it
  42932. * @param key the key to get the value from
  42933. * @param val if there's no such key/value pair in the dictionary add it with this value
  42934. * @return the value corresponding to the key
  42935. */
  42936. StringDictionary.prototype.getOrAdd = function (key, val) {
  42937. var curVal = this.get(key);
  42938. if (curVal !== undefined) {
  42939. return curVal;
  42940. }
  42941. this.add(key, val);
  42942. return val;
  42943. };
  42944. /**
  42945. * Check if there's a given key in the dictionary
  42946. * @param key the key to check for
  42947. * @return true if the key is present, false otherwise
  42948. */
  42949. StringDictionary.prototype.contains = function (key) {
  42950. return this._data[key] !== undefined;
  42951. };
  42952. /**
  42953. * Add a new key and its corresponding value
  42954. * @param key the key to add
  42955. * @param value the value corresponding to the key
  42956. * @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
  42957. */
  42958. StringDictionary.prototype.add = function (key, value) {
  42959. if (this._data[key] !== undefined) {
  42960. return false;
  42961. }
  42962. this._data[key] = value;
  42963. ++this._count;
  42964. return true;
  42965. };
  42966. StringDictionary.prototype.set = function (key, value) {
  42967. if (this._data[key] === undefined) {
  42968. return false;
  42969. }
  42970. this._data[key] = value;
  42971. return true;
  42972. };
  42973. /**
  42974. * Get the element of the given key and remove it from the dictionary
  42975. * @param key
  42976. */
  42977. StringDictionary.prototype.getAndRemove = function (key) {
  42978. var val = this.get(key);
  42979. if (val !== undefined) {
  42980. delete this._data[key];
  42981. --this._count;
  42982. return val;
  42983. }
  42984. return null;
  42985. };
  42986. /**
  42987. * Remove a key/value from the dictionary.
  42988. * @param key the key to remove
  42989. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  42990. */
  42991. StringDictionary.prototype.remove = function (key) {
  42992. if (this.contains(key)) {
  42993. delete this._data[key];
  42994. --this._count;
  42995. return true;
  42996. }
  42997. return false;
  42998. };
  42999. /**
  43000. * Clear the whole content of the dictionary
  43001. */
  43002. StringDictionary.prototype.clear = function () {
  43003. this._data = {};
  43004. this._count = 0;
  43005. };
  43006. Object.defineProperty(StringDictionary.prototype, "count", {
  43007. get: function () {
  43008. return this._count;
  43009. },
  43010. enumerable: true,
  43011. configurable: true
  43012. });
  43013. /**
  43014. * Execute a callback on each key/val of the dictionary.
  43015. * Note that you can remove any element in this dictionary in the callback implementation
  43016. * @param callback the callback to execute on a given key/value pair
  43017. */
  43018. StringDictionary.prototype.forEach = function (callback) {
  43019. for (var cur in this._data) {
  43020. var val = this._data[cur];
  43021. callback(cur, val);
  43022. }
  43023. };
  43024. /**
  43025. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  43026. * If the callback returns null or undefined the method will iterate to the next key/value pair
  43027. * Note that you can remove any element in this dictionary in the callback implementation
  43028. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  43029. */
  43030. StringDictionary.prototype.first = function (callback) {
  43031. for (var cur in this._data) {
  43032. var val = this._data[cur];
  43033. var res = callback(cur, val);
  43034. if (res) {
  43035. return res;
  43036. }
  43037. }
  43038. return null;
  43039. };
  43040. return StringDictionary;
  43041. }());
  43042. BABYLON.StringDictionary = StringDictionary;
  43043. })(BABYLON || (BABYLON = {}));
  43044. //# sourceMappingURL=babylon.stringDictionary.js.map
  43045. var BABYLON;
  43046. (function (BABYLON) {
  43047. var DynamicFloatArrayElementInfo = (function () {
  43048. function DynamicFloatArrayElementInfo() {
  43049. }
  43050. return DynamicFloatArrayElementInfo;
  43051. }());
  43052. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  43053. /**
  43054. * 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.
  43055. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  43056. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  43057. * 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.
  43058. * 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.
  43059. * 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".
  43060. */
  43061. var DynamicFloatArray = (function () {
  43062. /**
  43063. * Construct an instance of the dynamic float array
  43064. * @param stride size of one element in float (i.e. not bytes!)
  43065. * @param initialElementCount the number of available entries at construction
  43066. */
  43067. function DynamicFloatArray(stride, initialElementCount) {
  43068. this.compareValueOffset = null;
  43069. this.sortingAscending = true;
  43070. this._stride = stride;
  43071. this.buffer = new Float32Array(stride * initialElementCount);
  43072. this._lastUsed = 0;
  43073. this._firstFree = 0;
  43074. this._allEntries = new Array(initialElementCount);
  43075. this._freeEntries = new Array(initialElementCount);
  43076. for (var i = 0; i < initialElementCount; i++) {
  43077. var element = new DynamicFloatArrayElementInfo();
  43078. element.offset = i * stride;
  43079. this._allEntries[i] = element;
  43080. this._freeEntries[initialElementCount - i - 1] = element;
  43081. }
  43082. }
  43083. /**
  43084. * Allocate an element in the array.
  43085. * @return the element info instance that contains the offset into the main buffer of the element's location.
  43086. * Beware, this offset may change when you call pack()
  43087. */
  43088. DynamicFloatArray.prototype.allocElement = function () {
  43089. if (this._freeEntries.length === 0) {
  43090. this._growBuffer();
  43091. }
  43092. var el = this._freeEntries.pop();
  43093. this._lastUsed = Math.max(el.offset, this._lastUsed);
  43094. if (el.offset === this._firstFree) {
  43095. if (this._freeEntries.length > 0) {
  43096. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  43097. }
  43098. else {
  43099. this._firstFree += this._stride;
  43100. }
  43101. }
  43102. return el;
  43103. };
  43104. /**
  43105. * Free the element corresponding to the given element info
  43106. * @param elInfo the element that describe the allocated element
  43107. */
  43108. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43109. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43110. this._freeEntries.push(elInfo);
  43111. };
  43112. /**
  43113. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43114. * 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().
  43115. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43116. */
  43117. DynamicFloatArray.prototype.pack = function () {
  43118. // no free slot? no need to pack
  43119. if (this._freeEntries.length === 0) {
  43120. return this.buffer;
  43121. }
  43122. // If the buffer is already packed the last used will always be lower than the first free
  43123. // 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.
  43124. if (this._lastUsed < this._firstFree) {
  43125. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43126. return elementsBuffer_1;
  43127. }
  43128. var s = this._stride;
  43129. // 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
  43130. var lastFree = new DynamicFloatArrayElementInfo();
  43131. lastFree.offset = this.totalElementCount * s;
  43132. this._freeEntries.push(lastFree);
  43133. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43134. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43135. var firstFreeSlotOffset = sortedFree[0].offset;
  43136. var freeZoneSize = 1;
  43137. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43138. var prevOffset = sortedFree[0].offset;
  43139. for (var i = 1; i < sortedFree.length; i++) {
  43140. // 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
  43141. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43142. break;
  43143. }
  43144. var curFree = sortedFree[i];
  43145. var curOffset = curFree.offset;
  43146. // Compute the distance between this offset and the previous
  43147. var distance = curOffset - prevOffset;
  43148. // If the distance is the stride size, they are adjacent, it good, move to the next
  43149. if (distance === s) {
  43150. // Free zone is one element bigger
  43151. ++freeZoneSize;
  43152. // as we're about to iterate to the next, the cur becomes the previous...
  43153. prevOffset = curOffset;
  43154. continue;
  43155. }
  43156. // Distance is bigger, which means there's x element between the previous free and this one
  43157. var usedRange = (distance / s) - 1;
  43158. // Two cases the free zone is smaller than the data to move or bigger
  43159. // Copy what can fit in the free zone
  43160. var curMoveOffset = curOffset - s;
  43161. var copyCount = Math.min(freeZoneSize, usedRange);
  43162. for (var j = 0; j < copyCount; j++) {
  43163. var freeI = firstFreeSlotOffset / s;
  43164. var curI = curMoveOffset / s;
  43165. var moveEl = sortedAll[curI];
  43166. this._moveElement(moveEl, firstFreeSlotOffset);
  43167. var replacedEl = sortedAll[freeI];
  43168. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43169. replacedEl.offset = curMoveOffset;
  43170. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43171. sortedAll[freeI] = moveEl;
  43172. sortedAll[curI] = replacedEl;
  43173. curMoveOffset -= s;
  43174. firstFreeSlotOffset += s;
  43175. }
  43176. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43177. if (freeZoneSize <= usedRange) {
  43178. firstFreeSlotOffset = curMoveOffset + s;
  43179. freeZoneSize = 1 + copyCount;
  43180. }
  43181. else {
  43182. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43183. }
  43184. // as we're about to iterate to the next, the cur becomes the previous...
  43185. prevOffset = curOffset;
  43186. }
  43187. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43188. this._lastUsed = firstFreeSlotOffset - s;
  43189. this._firstFree = firstFreeSlotOffset;
  43190. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43191. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43192. this._allEntries = sortedAll;
  43193. return elementsBuffer;
  43194. };
  43195. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43196. for (var i = 0; i < this._stride; i++) {
  43197. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43198. }
  43199. element.offset = destOffset;
  43200. };
  43201. DynamicFloatArray.prototype._growBuffer = function () {
  43202. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43203. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43204. var newBuffer = new Float32Array(newElCount * this._stride);
  43205. newBuffer.set(this.buffer);
  43206. var curCount = this.totalElementCount;
  43207. var addedCount = newElCount - this.totalElementCount;
  43208. for (var i = 0; i < addedCount; i++) {
  43209. var element = new DynamicFloatArrayElementInfo();
  43210. element.offset = (curCount + i) * this.stride;
  43211. this._allEntries.push(element);
  43212. this._freeEntries[addedCount - i - 1] = element;
  43213. }
  43214. this._firstFree = curCount * this.stride;
  43215. this.buffer = newBuffer;
  43216. };
  43217. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43218. /**
  43219. * Get the total count of entries that can fit in the current buffer
  43220. * @returns the elements count
  43221. */
  43222. get: function () {
  43223. return this._allEntries.length;
  43224. },
  43225. enumerable: true,
  43226. configurable: true
  43227. });
  43228. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43229. /**
  43230. * Get the count of free entries that can still be allocated without resizing the buffer
  43231. * @returns the free elements count
  43232. */
  43233. get: function () {
  43234. return this._freeEntries.length;
  43235. },
  43236. enumerable: true,
  43237. configurable: true
  43238. });
  43239. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43240. /**
  43241. * Get the count of allocated elements
  43242. * @returns the allocated elements count
  43243. */
  43244. get: function () {
  43245. return this._allEntries.length - this._freeEntries.length;
  43246. },
  43247. enumerable: true,
  43248. configurable: true
  43249. });
  43250. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43251. /**
  43252. * Return the size of one element in float
  43253. * @returns the size in float
  43254. */
  43255. get: function () {
  43256. return this._stride;
  43257. },
  43258. enumerable: true,
  43259. configurable: true
  43260. });
  43261. DynamicFloatArray.prototype.sort = function () {
  43262. var _this = this;
  43263. if (!this.compareValueOffset) {
  43264. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43265. }
  43266. var count = this.usedElementCount;
  43267. // Do we have to (re)create the sort table?
  43268. if (!this._sortTable || this._sortTable.length < count) {
  43269. // 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...
  43270. var newCount = Math.min(this.totalElementCount, count * 2);
  43271. this._sortTable = new Array(newCount);
  43272. }
  43273. if (!this._sortedTable || this._sortedTable.length !== count) {
  43274. this._sortedTable = new Array(count);
  43275. }
  43276. // Because, you know...
  43277. this.pack();
  43278. //let stride = this.stride;
  43279. //for (let i = 0; i < count; i++) {
  43280. // let si = this._sortTable[i];
  43281. // if (!si) {
  43282. // si = new SortInfo();
  43283. // this._sortTable[i] = si;
  43284. // }
  43285. // si.entry = this._allEntries[i];
  43286. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43287. // si.swapedOffset = null;
  43288. // this._sortedTable[i] = si;
  43289. //}
  43290. var curOffset = 0;
  43291. var stride = this.stride;
  43292. for (var i = 0; i < count; i++, curOffset += stride) {
  43293. var si = this._sortTable[i];
  43294. if (!si) {
  43295. si = new SortInfo();
  43296. this._sortTable[i] = si;
  43297. }
  43298. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43299. si.offset = curOffset;
  43300. si.swapedOffset = null;
  43301. this._sortedTable[i] = si;
  43302. }
  43303. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43304. if (this.sortingAscending) {
  43305. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43306. }
  43307. else {
  43308. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43309. }
  43310. var swapElements = function (src, dst) {
  43311. for (var i = 0; i < stride; i++) {
  43312. var tps = _this.buffer[dst + i];
  43313. _this.buffer[dst + i] = _this.buffer[src + i];
  43314. _this.buffer[src + i] = tps;
  43315. }
  43316. };
  43317. // 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:
  43318. // 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),
  43319. // and I still want something with a good algorithm complexity.
  43320. // 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,
  43321. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43322. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43323. // 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
  43324. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43325. // 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
  43326. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43327. for (var i = 0; i < count; i++) {
  43328. // Get the element to move
  43329. var sourceSI = this._sortedTable[i];
  43330. var destSI = this._sortTable[i];
  43331. var sourceOff = sourceSI.offset;
  43332. // If the source changed location, find the new one
  43333. if (sourceSI.swapedOffset) {
  43334. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43335. var curSI = sourceSI;
  43336. while (curSI.swapedOffset) {
  43337. curSI = this._sortTable[curSI.swapedOffset / stride];
  43338. }
  43339. // Finally get the right location
  43340. sourceOff = curSI.offset;
  43341. }
  43342. // Tag the element being replaced with its new location
  43343. destSI.swapedOffset = sourceOff;
  43344. // Swap elements (only if needed)
  43345. if (sourceOff !== destSI.offset) {
  43346. swapElements(sourceOff, destSI.offset);
  43347. }
  43348. // Update the offset in the corresponding DFAE
  43349. //sourceSI.entry.offset = destSI.entry.offset;
  43350. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  43351. }
  43352. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43353. return true;
  43354. };
  43355. return DynamicFloatArray;
  43356. }());
  43357. BABYLON.DynamicFloatArray = DynamicFloatArray;
  43358. var SortInfo = (function () {
  43359. function SortInfo() {
  43360. this.compareData = this.offset = this.swapedOffset = null;
  43361. }
  43362. return SortInfo;
  43363. }());
  43364. })(BABYLON || (BABYLON = {}));
  43365. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  43366. var BABYLON;
  43367. (function (BABYLON) {
  43368. var Condition = (function () {
  43369. function Condition(actionManager) {
  43370. this._actionManager = actionManager;
  43371. }
  43372. Condition.prototype.isValid = function () {
  43373. return true;
  43374. };
  43375. Condition.prototype._getProperty = function (propertyPath) {
  43376. return this._actionManager._getProperty(propertyPath);
  43377. };
  43378. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43379. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43380. };
  43381. Condition.prototype.serialize = function () {
  43382. };
  43383. Condition.prototype._serialize = function (serializedCondition) {
  43384. return {
  43385. type: 2,
  43386. children: [],
  43387. name: serializedCondition.name,
  43388. properties: serializedCondition.properties
  43389. };
  43390. };
  43391. return Condition;
  43392. }());
  43393. BABYLON.Condition = Condition;
  43394. var ValueCondition = (function (_super) {
  43395. __extends(ValueCondition, _super);
  43396. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43397. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43398. var _this = _super.call(this, actionManager) || this;
  43399. _this.propertyPath = propertyPath;
  43400. _this.value = value;
  43401. _this.operator = operator;
  43402. _this._target = target;
  43403. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43404. _this._property = _this._getProperty(_this.propertyPath);
  43405. return _this;
  43406. }
  43407. Object.defineProperty(ValueCondition, "IsEqual", {
  43408. get: function () {
  43409. return ValueCondition._IsEqual;
  43410. },
  43411. enumerable: true,
  43412. configurable: true
  43413. });
  43414. Object.defineProperty(ValueCondition, "IsDifferent", {
  43415. get: function () {
  43416. return ValueCondition._IsDifferent;
  43417. },
  43418. enumerable: true,
  43419. configurable: true
  43420. });
  43421. Object.defineProperty(ValueCondition, "IsGreater", {
  43422. get: function () {
  43423. return ValueCondition._IsGreater;
  43424. },
  43425. enumerable: true,
  43426. configurable: true
  43427. });
  43428. Object.defineProperty(ValueCondition, "IsLesser", {
  43429. get: function () {
  43430. return ValueCondition._IsLesser;
  43431. },
  43432. enumerable: true,
  43433. configurable: true
  43434. });
  43435. // Methods
  43436. ValueCondition.prototype.isValid = function () {
  43437. switch (this.operator) {
  43438. case ValueCondition.IsGreater:
  43439. return this._effectiveTarget[this._property] > this.value;
  43440. case ValueCondition.IsLesser:
  43441. return this._effectiveTarget[this._property] < this.value;
  43442. case ValueCondition.IsEqual:
  43443. case ValueCondition.IsDifferent:
  43444. var check;
  43445. if (this.value.equals) {
  43446. check = this.value.equals(this._effectiveTarget[this._property]);
  43447. }
  43448. else {
  43449. check = this.value === this._effectiveTarget[this._property];
  43450. }
  43451. return this.operator === ValueCondition.IsEqual ? check : !check;
  43452. }
  43453. return false;
  43454. };
  43455. ValueCondition.prototype.serialize = function () {
  43456. return this._serialize({
  43457. name: "ValueCondition",
  43458. properties: [
  43459. BABYLON.Action._GetTargetProperty(this._target),
  43460. { name: "propertyPath", value: this.propertyPath },
  43461. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43462. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43463. ]
  43464. });
  43465. };
  43466. ValueCondition.GetOperatorName = function (operator) {
  43467. switch (operator) {
  43468. case ValueCondition._IsEqual: return "IsEqual";
  43469. case ValueCondition._IsDifferent: return "IsDifferent";
  43470. case ValueCondition._IsGreater: return "IsGreater";
  43471. case ValueCondition._IsLesser: return "IsLesser";
  43472. default: return "";
  43473. }
  43474. };
  43475. return ValueCondition;
  43476. }(Condition));
  43477. // Statics
  43478. ValueCondition._IsEqual = 0;
  43479. ValueCondition._IsDifferent = 1;
  43480. ValueCondition._IsGreater = 2;
  43481. ValueCondition._IsLesser = 3;
  43482. BABYLON.ValueCondition = ValueCondition;
  43483. var PredicateCondition = (function (_super) {
  43484. __extends(PredicateCondition, _super);
  43485. function PredicateCondition(actionManager, predicate) {
  43486. var _this = _super.call(this, actionManager) || this;
  43487. _this.predicate = predicate;
  43488. return _this;
  43489. }
  43490. PredicateCondition.prototype.isValid = function () {
  43491. return this.predicate();
  43492. };
  43493. return PredicateCondition;
  43494. }(Condition));
  43495. BABYLON.PredicateCondition = PredicateCondition;
  43496. var StateCondition = (function (_super) {
  43497. __extends(StateCondition, _super);
  43498. function StateCondition(actionManager, target, value) {
  43499. var _this = _super.call(this, actionManager) || this;
  43500. _this.value = value;
  43501. _this._target = target;
  43502. return _this;
  43503. }
  43504. // Methods
  43505. StateCondition.prototype.isValid = function () {
  43506. return this._target.state === this.value;
  43507. };
  43508. StateCondition.prototype.serialize = function () {
  43509. return this._serialize({
  43510. name: "StateCondition",
  43511. properties: [
  43512. BABYLON.Action._GetTargetProperty(this._target),
  43513. { name: "value", value: this.value }
  43514. ]
  43515. });
  43516. };
  43517. return StateCondition;
  43518. }(Condition));
  43519. BABYLON.StateCondition = StateCondition;
  43520. })(BABYLON || (BABYLON = {}));
  43521. //# sourceMappingURL=babylon.condition.js.map
  43522. var BABYLON;
  43523. (function (BABYLON) {
  43524. var Action = (function () {
  43525. function Action(triggerOptions, condition) {
  43526. this.triggerOptions = triggerOptions;
  43527. if (triggerOptions.parameter) {
  43528. this.trigger = triggerOptions.trigger;
  43529. this._triggerParameter = triggerOptions.parameter;
  43530. }
  43531. else {
  43532. this.trigger = triggerOptions;
  43533. }
  43534. this._nextActiveAction = this;
  43535. this._condition = condition;
  43536. }
  43537. // Methods
  43538. Action.prototype._prepare = function () {
  43539. };
  43540. Action.prototype.getTriggerParameter = function () {
  43541. return this._triggerParameter;
  43542. };
  43543. Action.prototype._executeCurrent = function (evt) {
  43544. if (this._nextActiveAction._condition) {
  43545. var condition = this._nextActiveAction._condition;
  43546. var currentRenderId = this._actionManager.getScene().getRenderId();
  43547. // We cache the current evaluation for the current frame
  43548. if (condition._evaluationId === currentRenderId) {
  43549. if (!condition._currentResult) {
  43550. return;
  43551. }
  43552. }
  43553. else {
  43554. condition._evaluationId = currentRenderId;
  43555. if (!condition.isValid()) {
  43556. condition._currentResult = false;
  43557. return;
  43558. }
  43559. condition._currentResult = true;
  43560. }
  43561. }
  43562. this._nextActiveAction.execute(evt);
  43563. this.skipToNextActiveAction();
  43564. };
  43565. Action.prototype.execute = function (evt) {
  43566. };
  43567. Action.prototype.skipToNextActiveAction = function () {
  43568. if (this._nextActiveAction._child) {
  43569. if (!this._nextActiveAction._child._actionManager) {
  43570. this._nextActiveAction._child._actionManager = this._actionManager;
  43571. }
  43572. this._nextActiveAction = this._nextActiveAction._child;
  43573. }
  43574. else {
  43575. this._nextActiveAction = this;
  43576. }
  43577. };
  43578. Action.prototype.then = function (action) {
  43579. this._child = action;
  43580. action._actionManager = this._actionManager;
  43581. action._prepare();
  43582. return action;
  43583. };
  43584. Action.prototype._getProperty = function (propertyPath) {
  43585. return this._actionManager._getProperty(propertyPath);
  43586. };
  43587. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43588. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43589. };
  43590. Action.prototype.serialize = function (parent) {
  43591. };
  43592. // Called by BABYLON.Action objects in serialize(...). Internal use
  43593. Action.prototype._serialize = function (serializedAction, parent) {
  43594. var serializationObject = {
  43595. type: 1,
  43596. children: [],
  43597. name: serializedAction.name,
  43598. properties: serializedAction.properties || []
  43599. };
  43600. // Serialize child
  43601. if (this._child) {
  43602. this._child.serialize(serializationObject);
  43603. }
  43604. // Check if "this" has a condition
  43605. if (this._condition) {
  43606. var serializedCondition = this._condition.serialize();
  43607. serializedCondition.children.push(serializationObject);
  43608. if (parent) {
  43609. parent.children.push(serializedCondition);
  43610. }
  43611. return serializedCondition;
  43612. }
  43613. if (parent) {
  43614. parent.children.push(serializationObject);
  43615. }
  43616. return serializationObject;
  43617. };
  43618. return Action;
  43619. }());
  43620. Action._SerializeValueAsString = function (value) {
  43621. if (typeof value === "number") {
  43622. return value.toString();
  43623. }
  43624. if (typeof value === "boolean") {
  43625. return value ? "true" : "false";
  43626. }
  43627. if (value instanceof BABYLON.Vector2) {
  43628. return value.x + ", " + value.y;
  43629. }
  43630. if (value instanceof BABYLON.Vector3) {
  43631. return value.x + ", " + value.y + ", " + value.z;
  43632. }
  43633. if (value instanceof BABYLON.Color3) {
  43634. return value.r + ", " + value.g + ", " + value.b;
  43635. }
  43636. if (value instanceof BABYLON.Color4) {
  43637. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43638. }
  43639. return value; // string
  43640. };
  43641. Action._GetTargetProperty = function (target) {
  43642. return {
  43643. name: "target",
  43644. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43645. : target instanceof BABYLON.Light ? "LightProperties"
  43646. : target instanceof BABYLON.Camera ? "CameraProperties"
  43647. : "SceneProperties",
  43648. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43649. };
  43650. };
  43651. BABYLON.Action = Action;
  43652. })(BABYLON || (BABYLON = {}));
  43653. //# sourceMappingURL=babylon.action.js.map
  43654. var BABYLON;
  43655. (function (BABYLON) {
  43656. /**
  43657. * ActionEvent is the event beint sent when an action is triggered.
  43658. */
  43659. var ActionEvent = (function () {
  43660. /**
  43661. * @constructor
  43662. * @param source The mesh or sprite that triggered the action.
  43663. * @param pointerX The X mouse cursor position at the time of the event
  43664. * @param pointerY The Y mouse cursor position at the time of the event
  43665. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43666. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43667. */
  43668. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43669. this.source = source;
  43670. this.pointerX = pointerX;
  43671. this.pointerY = pointerY;
  43672. this.meshUnderPointer = meshUnderPointer;
  43673. this.sourceEvent = sourceEvent;
  43674. this.additionalData = additionalData;
  43675. }
  43676. /**
  43677. * Helper function to auto-create an ActionEvent from a source mesh.
  43678. * @param source The source mesh that triggered the event
  43679. * @param evt {Event} The original (browser) event
  43680. */
  43681. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43682. var scene = source.getScene();
  43683. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43684. };
  43685. /**
  43686. * Helper function to auto-create an ActionEvent from a source mesh.
  43687. * @param source The source sprite that triggered the event
  43688. * @param scene Scene associated with the sprite
  43689. * @param evt {Event} The original (browser) event
  43690. */
  43691. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43692. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43693. };
  43694. /**
  43695. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43696. * @param scene the scene where the event occurred
  43697. * @param evt {Event} The original (browser) event
  43698. */
  43699. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43700. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43701. };
  43702. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43703. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43704. };
  43705. return ActionEvent;
  43706. }());
  43707. BABYLON.ActionEvent = ActionEvent;
  43708. /**
  43709. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43710. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43711. */
  43712. var ActionManager = (function () {
  43713. function ActionManager(scene) {
  43714. // Members
  43715. this.actions = new Array();
  43716. this.hoverCursor = '';
  43717. this._scene = scene;
  43718. scene._actionManagers.push(this);
  43719. }
  43720. Object.defineProperty(ActionManager, "NothingTrigger", {
  43721. get: function () {
  43722. return ActionManager._NothingTrigger;
  43723. },
  43724. enumerable: true,
  43725. configurable: true
  43726. });
  43727. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43728. get: function () {
  43729. return ActionManager._OnPickTrigger;
  43730. },
  43731. enumerable: true,
  43732. configurable: true
  43733. });
  43734. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43735. get: function () {
  43736. return ActionManager._OnLeftPickTrigger;
  43737. },
  43738. enumerable: true,
  43739. configurable: true
  43740. });
  43741. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43742. get: function () {
  43743. return ActionManager._OnRightPickTrigger;
  43744. },
  43745. enumerable: true,
  43746. configurable: true
  43747. });
  43748. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43749. get: function () {
  43750. return ActionManager._OnCenterPickTrigger;
  43751. },
  43752. enumerable: true,
  43753. configurable: true
  43754. });
  43755. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43756. get: function () {
  43757. return ActionManager._OnPickDownTrigger;
  43758. },
  43759. enumerable: true,
  43760. configurable: true
  43761. });
  43762. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43763. get: function () {
  43764. return ActionManager._OnDoublePickTrigger;
  43765. },
  43766. enumerable: true,
  43767. configurable: true
  43768. });
  43769. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43770. get: function () {
  43771. return ActionManager._OnPickUpTrigger;
  43772. },
  43773. enumerable: true,
  43774. configurable: true
  43775. });
  43776. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43777. /// This trigger will only be raised if you also declared a OnPickDown
  43778. get: function () {
  43779. return ActionManager._OnPickOutTrigger;
  43780. },
  43781. enumerable: true,
  43782. configurable: true
  43783. });
  43784. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43785. get: function () {
  43786. return ActionManager._OnLongPressTrigger;
  43787. },
  43788. enumerable: true,
  43789. configurable: true
  43790. });
  43791. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43792. get: function () {
  43793. return ActionManager._OnPointerOverTrigger;
  43794. },
  43795. enumerable: true,
  43796. configurable: true
  43797. });
  43798. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43799. get: function () {
  43800. return ActionManager._OnPointerOutTrigger;
  43801. },
  43802. enumerable: true,
  43803. configurable: true
  43804. });
  43805. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43806. get: function () {
  43807. return ActionManager._OnEveryFrameTrigger;
  43808. },
  43809. enumerable: true,
  43810. configurable: true
  43811. });
  43812. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43813. get: function () {
  43814. return ActionManager._OnIntersectionEnterTrigger;
  43815. },
  43816. enumerable: true,
  43817. configurable: true
  43818. });
  43819. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43820. get: function () {
  43821. return ActionManager._OnIntersectionExitTrigger;
  43822. },
  43823. enumerable: true,
  43824. configurable: true
  43825. });
  43826. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43827. get: function () {
  43828. return ActionManager._OnKeyDownTrigger;
  43829. },
  43830. enumerable: true,
  43831. configurable: true
  43832. });
  43833. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43834. get: function () {
  43835. return ActionManager._OnKeyUpTrigger;
  43836. },
  43837. enumerable: true,
  43838. configurable: true
  43839. });
  43840. // Methods
  43841. ActionManager.prototype.dispose = function () {
  43842. var index = this._scene._actionManagers.indexOf(this);
  43843. for (var i = 0; i < this.actions.length; i++) {
  43844. var action = this.actions[i];
  43845. ActionManager.Triggers[action.trigger]--;
  43846. if (ActionManager.Triggers[action.trigger] === 0) {
  43847. delete ActionManager.Triggers[action.trigger];
  43848. }
  43849. }
  43850. if (index > -1) {
  43851. this._scene._actionManagers.splice(index, 1);
  43852. }
  43853. };
  43854. ActionManager.prototype.getScene = function () {
  43855. return this._scene;
  43856. };
  43857. /**
  43858. * Does this action manager handles actions of any of the given triggers
  43859. * @param {number[]} triggers - the triggers to be tested
  43860. * @return {boolean} whether one (or more) of the triggers is handeled
  43861. */
  43862. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43863. for (var index = 0; index < this.actions.length; index++) {
  43864. var action = this.actions[index];
  43865. if (triggers.indexOf(action.trigger) > -1) {
  43866. return true;
  43867. }
  43868. }
  43869. return false;
  43870. };
  43871. /**
  43872. * Does this action manager handles actions of a given trigger
  43873. * @param {number} trigger - the trigger to be tested
  43874. * @return {boolean} whether the trigger is handeled
  43875. */
  43876. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43877. for (var index = 0; index < this.actions.length; index++) {
  43878. var action = this.actions[index];
  43879. if (action.trigger === trigger) {
  43880. return true;
  43881. }
  43882. }
  43883. return false;
  43884. };
  43885. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43886. /**
  43887. * Does this action manager has pointer triggers
  43888. * @return {boolean} whether or not it has pointer triggers
  43889. */
  43890. get: function () {
  43891. for (var index = 0; index < this.actions.length; index++) {
  43892. var action = this.actions[index];
  43893. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43894. return true;
  43895. }
  43896. }
  43897. return false;
  43898. },
  43899. enumerable: true,
  43900. configurable: true
  43901. });
  43902. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43903. /**
  43904. * Does this action manager has pick triggers
  43905. * @return {boolean} whether or not it has pick triggers
  43906. */
  43907. get: function () {
  43908. for (var index = 0; index < this.actions.length; index++) {
  43909. var action = this.actions[index];
  43910. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43911. return true;
  43912. }
  43913. }
  43914. return false;
  43915. },
  43916. enumerable: true,
  43917. configurable: true
  43918. });
  43919. Object.defineProperty(ActionManager, "HasTriggers", {
  43920. /**
  43921. * Does exist one action manager with at least one trigger
  43922. * @return {boolean} whether or not it exists one action manager with one trigger
  43923. **/
  43924. get: function () {
  43925. for (var t in ActionManager.Triggers) {
  43926. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43927. return true;
  43928. }
  43929. }
  43930. return false;
  43931. },
  43932. enumerable: true,
  43933. configurable: true
  43934. });
  43935. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43936. /**
  43937. * Does exist one action manager with at least one pick trigger
  43938. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43939. **/
  43940. get: function () {
  43941. for (var t in ActionManager.Triggers) {
  43942. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43943. var t_int = parseInt(t);
  43944. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43945. return true;
  43946. }
  43947. }
  43948. }
  43949. return false;
  43950. },
  43951. enumerable: true,
  43952. configurable: true
  43953. });
  43954. /**
  43955. * Does exist one action manager that handles actions of a given trigger
  43956. * @param {number} trigger - the trigger to be tested
  43957. * @return {boolean} whether the trigger is handeled by at least one action manager
  43958. **/
  43959. ActionManager.HasSpecificTrigger = function (trigger) {
  43960. for (var t in ActionManager.Triggers) {
  43961. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43962. var t_int = parseInt(t);
  43963. if (t_int === trigger) {
  43964. return true;
  43965. }
  43966. }
  43967. }
  43968. return false;
  43969. };
  43970. /**
  43971. * Registers an action to this action manager
  43972. * @param {BABYLON.Action} action - the action to be registered
  43973. * @return {BABYLON.Action} the action amended (prepared) after registration
  43974. */
  43975. ActionManager.prototype.registerAction = function (action) {
  43976. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43977. if (this.getScene().actionManager !== this) {
  43978. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43979. return null;
  43980. }
  43981. }
  43982. this.actions.push(action);
  43983. if (ActionManager.Triggers[action.trigger]) {
  43984. ActionManager.Triggers[action.trigger]++;
  43985. }
  43986. else {
  43987. ActionManager.Triggers[action.trigger] = 1;
  43988. }
  43989. action._actionManager = this;
  43990. action._prepare();
  43991. return action;
  43992. };
  43993. /**
  43994. * Process a specific trigger
  43995. * @param {number} trigger - the trigger to process
  43996. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43997. */
  43998. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43999. for (var index = 0; index < this.actions.length; index++) {
  44000. var action = this.actions[index];
  44001. if (action.trigger === trigger) {
  44002. if (trigger === ActionManager.OnKeyUpTrigger
  44003. || trigger === ActionManager.OnKeyDownTrigger) {
  44004. var parameter = action.getTriggerParameter();
  44005. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44006. if (!parameter.toLowerCase) {
  44007. continue;
  44008. }
  44009. var lowerCase = parameter.toLowerCase();
  44010. if (lowerCase !== evt.sourceEvent.key) {
  44011. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44012. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44013. if (actualkey !== lowerCase) {
  44014. continue;
  44015. }
  44016. }
  44017. }
  44018. }
  44019. action._executeCurrent(evt);
  44020. }
  44021. }
  44022. };
  44023. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44024. var properties = propertyPath.split(".");
  44025. for (var index = 0; index < properties.length - 1; index++) {
  44026. target = target[properties[index]];
  44027. }
  44028. return target;
  44029. };
  44030. ActionManager.prototype._getProperty = function (propertyPath) {
  44031. var properties = propertyPath.split(".");
  44032. return properties[properties.length - 1];
  44033. };
  44034. ActionManager.prototype.serialize = function (name) {
  44035. var root = {
  44036. children: [],
  44037. name: name,
  44038. type: 3,
  44039. properties: [] // Empty for root but required
  44040. };
  44041. for (var i = 0; i < this.actions.length; i++) {
  44042. var triggerObject = {
  44043. type: 0,
  44044. children: [],
  44045. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44046. properties: []
  44047. };
  44048. var triggerOptions = this.actions[i].triggerOptions;
  44049. if (triggerOptions && typeof triggerOptions !== "number") {
  44050. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44051. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44052. }
  44053. else {
  44054. var parameter = {};
  44055. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44056. if (triggerOptions.parameter.mesh) {
  44057. parameter._meshId = triggerOptions.parameter.mesh.id;
  44058. }
  44059. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44060. }
  44061. }
  44062. // Serialize child action, recursively
  44063. this.actions[i].serialize(triggerObject);
  44064. // Add serialized trigger
  44065. root.children.push(triggerObject);
  44066. }
  44067. return root;
  44068. };
  44069. ActionManager.Parse = function (parsedActions, object, scene) {
  44070. var actionManager = new BABYLON.ActionManager(scene);
  44071. if (object === null)
  44072. scene.actionManager = actionManager;
  44073. else
  44074. object.actionManager = actionManager;
  44075. // instanciate a new object
  44076. var instanciate = function (name, params) {
  44077. var newInstance = Object.create(BABYLON[name].prototype);
  44078. newInstance.constructor.apply(newInstance, params);
  44079. return newInstance;
  44080. };
  44081. var parseParameter = function (name, value, target, propertyPath) {
  44082. if (propertyPath === null) {
  44083. // String, boolean or float
  44084. var floatValue = parseFloat(value);
  44085. if (value === "true" || value === "false")
  44086. return value === "true";
  44087. else
  44088. return isNaN(floatValue) ? value : floatValue;
  44089. }
  44090. var effectiveTarget = propertyPath.split(".");
  44091. var values = value.split(",");
  44092. // Get effective Target
  44093. for (var i = 0; i < effectiveTarget.length; i++) {
  44094. target = target[effectiveTarget[i]];
  44095. }
  44096. // Return appropriate value with its type
  44097. if (typeof (target) === "boolean")
  44098. return values[0] === "true";
  44099. if (typeof (target) === "string")
  44100. return values[0];
  44101. // Parameters with multiple values such as Vector3 etc.
  44102. var split = new Array();
  44103. for (var i = 0; i < values.length; i++)
  44104. split.push(parseFloat(values[i]));
  44105. if (target instanceof BABYLON.Vector3)
  44106. return BABYLON.Vector3.FromArray(split);
  44107. if (target instanceof BABYLON.Vector4)
  44108. return BABYLON.Vector4.FromArray(split);
  44109. if (target instanceof BABYLON.Color3)
  44110. return BABYLON.Color3.FromArray(split);
  44111. if (target instanceof BABYLON.Color4)
  44112. return BABYLON.Color4.FromArray(split);
  44113. return parseFloat(values[0]);
  44114. };
  44115. // traverse graph per trigger
  44116. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44117. if (combineArray === void 0) { combineArray = null; }
  44118. if (parsedAction.detached)
  44119. return;
  44120. var parameters = new Array();
  44121. var target = null;
  44122. var propertyPath = null;
  44123. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44124. // Parameters
  44125. if (parsedAction.type === 2)
  44126. parameters.push(actionManager);
  44127. else
  44128. parameters.push(trigger);
  44129. if (combine) {
  44130. var actions = new Array();
  44131. for (var j = 0; j < parsedAction.combine.length; j++) {
  44132. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44133. }
  44134. parameters.push(actions);
  44135. }
  44136. else {
  44137. for (var i = 0; i < parsedAction.properties.length; i++) {
  44138. var value = parsedAction.properties[i].value;
  44139. var name = parsedAction.properties[i].name;
  44140. var targetType = parsedAction.properties[i].targetType;
  44141. if (name === "target")
  44142. if (targetType !== null && targetType === "SceneProperties")
  44143. value = target = scene;
  44144. else
  44145. value = target = scene.getNodeByName(value);
  44146. else if (name === "parent")
  44147. value = scene.getNodeByName(value);
  44148. else if (name === "sound")
  44149. value = scene.getSoundByName(value);
  44150. else if (name !== "propertyPath") {
  44151. if (parsedAction.type === 2 && name === "operator")
  44152. value = BABYLON.ValueCondition[value];
  44153. else
  44154. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44155. }
  44156. else {
  44157. propertyPath = value;
  44158. }
  44159. parameters.push(value);
  44160. }
  44161. }
  44162. if (combineArray === null) {
  44163. parameters.push(condition);
  44164. }
  44165. else {
  44166. parameters.push(null);
  44167. }
  44168. // If interpolate value action
  44169. if (parsedAction.name === "InterpolateValueAction") {
  44170. var param = parameters[parameters.length - 2];
  44171. parameters[parameters.length - 1] = param;
  44172. parameters[parameters.length - 2] = condition;
  44173. }
  44174. // Action or condition(s) and not CombineAction
  44175. var newAction = instanciate(parsedAction.name, parameters);
  44176. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44177. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44178. if (action)
  44179. action.then(nothing);
  44180. else
  44181. actionManager.registerAction(nothing);
  44182. action = nothing;
  44183. }
  44184. if (combineArray === null) {
  44185. if (newAction instanceof BABYLON.Condition) {
  44186. condition = newAction;
  44187. newAction = action;
  44188. }
  44189. else {
  44190. condition = null;
  44191. if (action)
  44192. action.then(newAction);
  44193. else
  44194. actionManager.registerAction(newAction);
  44195. }
  44196. }
  44197. else {
  44198. combineArray.push(newAction);
  44199. }
  44200. for (var i = 0; i < parsedAction.children.length; i++)
  44201. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44202. };
  44203. // triggers
  44204. for (var i = 0; i < parsedActions.children.length; i++) {
  44205. var triggerParams;
  44206. var trigger = parsedActions.children[i];
  44207. if (trigger.properties.length > 0) {
  44208. var param = trigger.properties[0].value;
  44209. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44210. if (value._meshId) {
  44211. value.mesh = scene.getMeshByID(value._meshId);
  44212. }
  44213. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  44214. }
  44215. else
  44216. triggerParams = BABYLON.ActionManager[trigger.name];
  44217. for (var j = 0; j < trigger.children.length; j++) {
  44218. if (!trigger.detached)
  44219. traverse(trigger.children[j], triggerParams, null, null);
  44220. }
  44221. }
  44222. };
  44223. ActionManager.GetTriggerName = function (trigger) {
  44224. switch (trigger) {
  44225. case 0: return "NothingTrigger";
  44226. case 1: return "OnPickTrigger";
  44227. case 2: return "OnLeftPickTrigger";
  44228. case 3: return "OnRightPickTrigger";
  44229. case 4: return "OnCenterPickTrigger";
  44230. case 5: return "OnPickDownTrigger";
  44231. case 6: return "OnPickUpTrigger";
  44232. case 7: return "OnLongPressTrigger";
  44233. case 8: return "OnPointerOverTrigger";
  44234. case 9: return "OnPointerOutTrigger";
  44235. case 10: return "OnEveryFrameTrigger";
  44236. case 11: return "OnIntersectionEnterTrigger";
  44237. case 12: return "OnIntersectionExitTrigger";
  44238. case 13: return "OnKeyDownTrigger";
  44239. case 14: return "OnKeyUpTrigger";
  44240. case 15: return "OnPickOutTrigger";
  44241. default: return "";
  44242. }
  44243. };
  44244. return ActionManager;
  44245. }());
  44246. // Statics
  44247. ActionManager._NothingTrigger = 0;
  44248. ActionManager._OnPickTrigger = 1;
  44249. ActionManager._OnLeftPickTrigger = 2;
  44250. ActionManager._OnRightPickTrigger = 3;
  44251. ActionManager._OnCenterPickTrigger = 4;
  44252. ActionManager._OnPickDownTrigger = 5;
  44253. ActionManager._OnDoublePickTrigger = 6;
  44254. ActionManager._OnPickUpTrigger = 7;
  44255. ActionManager._OnLongPressTrigger = 8;
  44256. ActionManager._OnPointerOverTrigger = 9;
  44257. ActionManager._OnPointerOutTrigger = 10;
  44258. ActionManager._OnEveryFrameTrigger = 11;
  44259. ActionManager._OnIntersectionEnterTrigger = 12;
  44260. ActionManager._OnIntersectionExitTrigger = 13;
  44261. ActionManager._OnKeyDownTrigger = 14;
  44262. ActionManager._OnKeyUpTrigger = 15;
  44263. ActionManager._OnPickOutTrigger = 16;
  44264. ActionManager.Triggers = {};
  44265. BABYLON.ActionManager = ActionManager;
  44266. })(BABYLON || (BABYLON = {}));
  44267. //# sourceMappingURL=babylon.actionManager.js.map
  44268. var BABYLON;
  44269. (function (BABYLON) {
  44270. var InterpolateValueAction = (function (_super) {
  44271. __extends(InterpolateValueAction, _super);
  44272. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44273. if (duration === void 0) { duration = 1000; }
  44274. var _this = _super.call(this, triggerOptions, condition) || this;
  44275. _this.propertyPath = propertyPath;
  44276. _this.value = value;
  44277. _this.duration = duration;
  44278. _this.stopOtherAnimations = stopOtherAnimations;
  44279. _this.onInterpolationDone = onInterpolationDone;
  44280. _this._target = _this._effectiveTarget = target;
  44281. return _this;
  44282. }
  44283. InterpolateValueAction.prototype._prepare = function () {
  44284. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44285. this._property = this._getProperty(this.propertyPath);
  44286. };
  44287. InterpolateValueAction.prototype.execute = function () {
  44288. var scene = this._actionManager.getScene();
  44289. var keys = [
  44290. {
  44291. frame: 0,
  44292. value: this._effectiveTarget[this._property]
  44293. }, {
  44294. frame: 100,
  44295. value: this.value
  44296. }
  44297. ];
  44298. var dataType;
  44299. if (typeof this.value === "number") {
  44300. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44301. }
  44302. else if (this.value instanceof BABYLON.Color3) {
  44303. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44304. }
  44305. else if (this.value instanceof BABYLON.Vector3) {
  44306. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44307. }
  44308. else if (this.value instanceof BABYLON.Matrix) {
  44309. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44310. }
  44311. else if (this.value instanceof BABYLON.Quaternion) {
  44312. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44313. }
  44314. else {
  44315. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44316. return;
  44317. }
  44318. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44319. animation.setKeys(keys);
  44320. if (this.stopOtherAnimations) {
  44321. scene.stopAnimation(this._effectiveTarget);
  44322. }
  44323. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  44324. };
  44325. InterpolateValueAction.prototype.serialize = function (parent) {
  44326. return _super.prototype._serialize.call(this, {
  44327. name: "InterpolateValueAction",
  44328. properties: [
  44329. BABYLON.Action._GetTargetProperty(this._target),
  44330. { name: "propertyPath", value: this.propertyPath },
  44331. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44332. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44333. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44334. ]
  44335. }, parent);
  44336. };
  44337. return InterpolateValueAction;
  44338. }(BABYLON.Action));
  44339. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44340. })(BABYLON || (BABYLON = {}));
  44341. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44342. var BABYLON;
  44343. (function (BABYLON) {
  44344. var SwitchBooleanAction = (function (_super) {
  44345. __extends(SwitchBooleanAction, _super);
  44346. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44347. var _this = _super.call(this, triggerOptions, condition) || this;
  44348. _this.propertyPath = propertyPath;
  44349. _this._target = _this._effectiveTarget = target;
  44350. return _this;
  44351. }
  44352. SwitchBooleanAction.prototype._prepare = function () {
  44353. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44354. this._property = this._getProperty(this.propertyPath);
  44355. };
  44356. SwitchBooleanAction.prototype.execute = function () {
  44357. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44358. };
  44359. SwitchBooleanAction.prototype.serialize = function (parent) {
  44360. return _super.prototype._serialize.call(this, {
  44361. name: "SwitchBooleanAction",
  44362. properties: [
  44363. BABYLON.Action._GetTargetProperty(this._target),
  44364. { name: "propertyPath", value: this.propertyPath }
  44365. ]
  44366. }, parent);
  44367. };
  44368. return SwitchBooleanAction;
  44369. }(BABYLON.Action));
  44370. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44371. var SetStateAction = (function (_super) {
  44372. __extends(SetStateAction, _super);
  44373. function SetStateAction(triggerOptions, target, value, condition) {
  44374. var _this = _super.call(this, triggerOptions, condition) || this;
  44375. _this.value = value;
  44376. _this._target = target;
  44377. return _this;
  44378. }
  44379. SetStateAction.prototype.execute = function () {
  44380. this._target.state = this.value;
  44381. };
  44382. SetStateAction.prototype.serialize = function (parent) {
  44383. return _super.prototype._serialize.call(this, {
  44384. name: "SetStateAction",
  44385. properties: [
  44386. BABYLON.Action._GetTargetProperty(this._target),
  44387. { name: "value", value: this.value }
  44388. ]
  44389. }, parent);
  44390. };
  44391. return SetStateAction;
  44392. }(BABYLON.Action));
  44393. BABYLON.SetStateAction = SetStateAction;
  44394. var SetValueAction = (function (_super) {
  44395. __extends(SetValueAction, _super);
  44396. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44397. var _this = _super.call(this, triggerOptions, condition) || this;
  44398. _this.propertyPath = propertyPath;
  44399. _this.value = value;
  44400. _this._target = _this._effectiveTarget = target;
  44401. return _this;
  44402. }
  44403. SetValueAction.prototype._prepare = function () {
  44404. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44405. this._property = this._getProperty(this.propertyPath);
  44406. };
  44407. SetValueAction.prototype.execute = function () {
  44408. this._effectiveTarget[this._property] = this.value;
  44409. if (this._target.markAsDirty) {
  44410. this._target.markAsDirty(this._property);
  44411. }
  44412. };
  44413. SetValueAction.prototype.serialize = function (parent) {
  44414. return _super.prototype._serialize.call(this, {
  44415. name: "SetValueAction",
  44416. properties: [
  44417. BABYLON.Action._GetTargetProperty(this._target),
  44418. { name: "propertyPath", value: this.propertyPath },
  44419. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44420. ]
  44421. }, parent);
  44422. };
  44423. return SetValueAction;
  44424. }(BABYLON.Action));
  44425. BABYLON.SetValueAction = SetValueAction;
  44426. var IncrementValueAction = (function (_super) {
  44427. __extends(IncrementValueAction, _super);
  44428. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44429. var _this = _super.call(this, triggerOptions, condition) || this;
  44430. _this.propertyPath = propertyPath;
  44431. _this.value = value;
  44432. _this._target = _this._effectiveTarget = target;
  44433. return _this;
  44434. }
  44435. IncrementValueAction.prototype._prepare = function () {
  44436. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44437. this._property = this._getProperty(this.propertyPath);
  44438. if (typeof this._effectiveTarget[this._property] !== "number") {
  44439. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44440. }
  44441. };
  44442. IncrementValueAction.prototype.execute = function () {
  44443. this._effectiveTarget[this._property] += this.value;
  44444. if (this._target.markAsDirty) {
  44445. this._target.markAsDirty(this._property);
  44446. }
  44447. };
  44448. IncrementValueAction.prototype.serialize = function (parent) {
  44449. return _super.prototype._serialize.call(this, {
  44450. name: "IncrementValueAction",
  44451. properties: [
  44452. BABYLON.Action._GetTargetProperty(this._target),
  44453. { name: "propertyPath", value: this.propertyPath },
  44454. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44455. ]
  44456. }, parent);
  44457. };
  44458. return IncrementValueAction;
  44459. }(BABYLON.Action));
  44460. BABYLON.IncrementValueAction = IncrementValueAction;
  44461. var PlayAnimationAction = (function (_super) {
  44462. __extends(PlayAnimationAction, _super);
  44463. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44464. var _this = _super.call(this, triggerOptions, condition) || this;
  44465. _this.from = from;
  44466. _this.to = to;
  44467. _this.loop = loop;
  44468. _this._target = target;
  44469. return _this;
  44470. }
  44471. PlayAnimationAction.prototype._prepare = function () {
  44472. };
  44473. PlayAnimationAction.prototype.execute = function () {
  44474. var scene = this._actionManager.getScene();
  44475. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44476. };
  44477. PlayAnimationAction.prototype.serialize = function (parent) {
  44478. return _super.prototype._serialize.call(this, {
  44479. name: "PlayAnimationAction",
  44480. properties: [
  44481. BABYLON.Action._GetTargetProperty(this._target),
  44482. { name: "from", value: String(this.from) },
  44483. { name: "to", value: String(this.to) },
  44484. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44485. ]
  44486. }, parent);
  44487. };
  44488. return PlayAnimationAction;
  44489. }(BABYLON.Action));
  44490. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44491. var StopAnimationAction = (function (_super) {
  44492. __extends(StopAnimationAction, _super);
  44493. function StopAnimationAction(triggerOptions, target, condition) {
  44494. var _this = _super.call(this, triggerOptions, condition) || this;
  44495. _this._target = target;
  44496. return _this;
  44497. }
  44498. StopAnimationAction.prototype._prepare = function () {
  44499. };
  44500. StopAnimationAction.prototype.execute = function () {
  44501. var scene = this._actionManager.getScene();
  44502. scene.stopAnimation(this._target);
  44503. };
  44504. StopAnimationAction.prototype.serialize = function (parent) {
  44505. return _super.prototype._serialize.call(this, {
  44506. name: "StopAnimationAction",
  44507. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44508. }, parent);
  44509. };
  44510. return StopAnimationAction;
  44511. }(BABYLON.Action));
  44512. BABYLON.StopAnimationAction = StopAnimationAction;
  44513. var DoNothingAction = (function (_super) {
  44514. __extends(DoNothingAction, _super);
  44515. function DoNothingAction(triggerOptions, condition) {
  44516. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44517. return _super.call(this, triggerOptions, condition) || this;
  44518. }
  44519. DoNothingAction.prototype.execute = function () {
  44520. };
  44521. DoNothingAction.prototype.serialize = function (parent) {
  44522. return _super.prototype._serialize.call(this, {
  44523. name: "DoNothingAction",
  44524. properties: []
  44525. }, parent);
  44526. };
  44527. return DoNothingAction;
  44528. }(BABYLON.Action));
  44529. BABYLON.DoNothingAction = DoNothingAction;
  44530. var CombineAction = (function (_super) {
  44531. __extends(CombineAction, _super);
  44532. function CombineAction(triggerOptions, children, condition) {
  44533. var _this = _super.call(this, triggerOptions, condition) || this;
  44534. _this.children = children;
  44535. return _this;
  44536. }
  44537. CombineAction.prototype._prepare = function () {
  44538. for (var index = 0; index < this.children.length; index++) {
  44539. this.children[index]._actionManager = this._actionManager;
  44540. this.children[index]._prepare();
  44541. }
  44542. };
  44543. CombineAction.prototype.execute = function (evt) {
  44544. for (var index = 0; index < this.children.length; index++) {
  44545. this.children[index].execute(evt);
  44546. }
  44547. };
  44548. CombineAction.prototype.serialize = function (parent) {
  44549. var serializationObject = _super.prototype._serialize.call(this, {
  44550. name: "CombineAction",
  44551. properties: [],
  44552. combine: []
  44553. }, parent);
  44554. for (var i = 0; i < this.children.length; i++) {
  44555. serializationObject.combine.push(this.children[i].serialize(null));
  44556. }
  44557. return serializationObject;
  44558. };
  44559. return CombineAction;
  44560. }(BABYLON.Action));
  44561. BABYLON.CombineAction = CombineAction;
  44562. var ExecuteCodeAction = (function (_super) {
  44563. __extends(ExecuteCodeAction, _super);
  44564. function ExecuteCodeAction(triggerOptions, func, condition) {
  44565. var _this = _super.call(this, triggerOptions, condition) || this;
  44566. _this.func = func;
  44567. return _this;
  44568. }
  44569. ExecuteCodeAction.prototype.execute = function (evt) {
  44570. this.func(evt);
  44571. };
  44572. return ExecuteCodeAction;
  44573. }(BABYLON.Action));
  44574. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44575. var SetParentAction = (function (_super) {
  44576. __extends(SetParentAction, _super);
  44577. function SetParentAction(triggerOptions, target, parent, condition) {
  44578. var _this = _super.call(this, triggerOptions, condition) || this;
  44579. _this._target = target;
  44580. _this._parent = parent;
  44581. return _this;
  44582. }
  44583. SetParentAction.prototype._prepare = function () {
  44584. };
  44585. SetParentAction.prototype.execute = function () {
  44586. if (this._target.parent === this._parent) {
  44587. return;
  44588. }
  44589. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44590. invertParentWorldMatrix.invert();
  44591. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44592. this._target.parent = this._parent;
  44593. };
  44594. SetParentAction.prototype.serialize = function (parent) {
  44595. return _super.prototype._serialize.call(this, {
  44596. name: "SetParentAction",
  44597. properties: [
  44598. BABYLON.Action._GetTargetProperty(this._target),
  44599. BABYLON.Action._GetTargetProperty(this._parent),
  44600. ]
  44601. }, parent);
  44602. };
  44603. return SetParentAction;
  44604. }(BABYLON.Action));
  44605. BABYLON.SetParentAction = SetParentAction;
  44606. var PlaySoundAction = (function (_super) {
  44607. __extends(PlaySoundAction, _super);
  44608. function PlaySoundAction(triggerOptions, sound, condition) {
  44609. var _this = _super.call(this, triggerOptions, condition) || this;
  44610. _this._sound = sound;
  44611. return _this;
  44612. }
  44613. PlaySoundAction.prototype._prepare = function () {
  44614. };
  44615. PlaySoundAction.prototype.execute = function () {
  44616. if (this._sound !== undefined)
  44617. this._sound.play();
  44618. };
  44619. PlaySoundAction.prototype.serialize = function (parent) {
  44620. return _super.prototype._serialize.call(this, {
  44621. name: "PlaySoundAction",
  44622. properties: [{ name: "sound", value: this._sound.name }]
  44623. }, parent);
  44624. };
  44625. return PlaySoundAction;
  44626. }(BABYLON.Action));
  44627. BABYLON.PlaySoundAction = PlaySoundAction;
  44628. var StopSoundAction = (function (_super) {
  44629. __extends(StopSoundAction, _super);
  44630. function StopSoundAction(triggerOptions, sound, condition) {
  44631. var _this = _super.call(this, triggerOptions, condition) || this;
  44632. _this._sound = sound;
  44633. return _this;
  44634. }
  44635. StopSoundAction.prototype._prepare = function () {
  44636. };
  44637. StopSoundAction.prototype.execute = function () {
  44638. if (this._sound !== undefined)
  44639. this._sound.stop();
  44640. };
  44641. StopSoundAction.prototype.serialize = function (parent) {
  44642. return _super.prototype._serialize.call(this, {
  44643. name: "StopSoundAction",
  44644. properties: [{ name: "sound", value: this._sound.name }]
  44645. }, parent);
  44646. };
  44647. return StopSoundAction;
  44648. }(BABYLON.Action));
  44649. BABYLON.StopSoundAction = StopSoundAction;
  44650. })(BABYLON || (BABYLON = {}));
  44651. //# sourceMappingURL=babylon.directActions.js.map
  44652. var BABYLON;
  44653. (function (BABYLON) {
  44654. var Debug;
  44655. (function (Debug) {
  44656. /**
  44657. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  44658. */
  44659. var SkeletonViewer = (function () {
  44660. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  44661. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  44662. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  44663. this.skeleton = skeleton;
  44664. this.mesh = mesh;
  44665. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  44666. this.renderingGroupId = renderingGroupId;
  44667. this.color = BABYLON.Color3.White();
  44668. this._debugLines = [];
  44669. this._isEnabled = false;
  44670. this._scene = scene;
  44671. this.update();
  44672. this._renderFunction = this.update.bind(this);
  44673. }
  44674. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  44675. get: function () {
  44676. return this._isEnabled;
  44677. },
  44678. set: function (value) {
  44679. if (this._isEnabled === value) {
  44680. return;
  44681. }
  44682. this._isEnabled = value;
  44683. if (value) {
  44684. this._scene.registerBeforeRender(this._renderFunction);
  44685. }
  44686. else {
  44687. this._scene.unregisterBeforeRender(this._renderFunction);
  44688. }
  44689. },
  44690. enumerable: true,
  44691. configurable: true
  44692. });
  44693. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  44694. if (x === void 0) { x = 0; }
  44695. if (y === void 0) { y = 0; }
  44696. if (z === void 0) { z = 0; }
  44697. var tmat = BABYLON.Tmp.Matrix[0];
  44698. var parentBone = bone.getParent();
  44699. tmat.copyFrom(bone.getLocalMatrix());
  44700. if (x !== 0 || y !== 0 || z !== 0) {
  44701. var tmat2 = BABYLON.Tmp.Matrix[1];
  44702. BABYLON.Matrix.IdentityToRef(tmat2);
  44703. tmat2.m[12] = x;
  44704. tmat2.m[13] = y;
  44705. tmat2.m[14] = z;
  44706. tmat2.multiplyToRef(tmat, tmat);
  44707. }
  44708. if (parentBone) {
  44709. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44710. }
  44711. tmat.multiplyToRef(meshMat, tmat);
  44712. position.x = tmat.m[12];
  44713. position.y = tmat.m[13];
  44714. position.z = tmat.m[14];
  44715. };
  44716. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44717. var len = bones.length;
  44718. var meshPos = this.mesh.position;
  44719. for (var i = 0; i < len; i++) {
  44720. var bone = bones[i];
  44721. var points = this._debugLines[i];
  44722. if (!points) {
  44723. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44724. this._debugLines[i] = points;
  44725. }
  44726. this._getBonePosition(points[0], bone, meshMat);
  44727. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44728. points[0].subtractInPlace(meshPos);
  44729. points[1].subtractInPlace(meshPos);
  44730. }
  44731. };
  44732. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44733. var len = bones.length;
  44734. var boneNum = 0;
  44735. var meshPos = this.mesh.position;
  44736. for (var i = len - 1; i >= 0; i--) {
  44737. var childBone = bones[i];
  44738. var parentBone = childBone.getParent();
  44739. if (!parentBone) {
  44740. continue;
  44741. }
  44742. var points = this._debugLines[boneNum];
  44743. if (!points) {
  44744. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44745. this._debugLines[boneNum] = points;
  44746. }
  44747. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  44748. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  44749. points[0].subtractInPlace(meshPos);
  44750. points[1].subtractInPlace(meshPos);
  44751. boneNum++;
  44752. }
  44753. };
  44754. SkeletonViewer.prototype.update = function () {
  44755. if (this.autoUpdateBonesMatrices) {
  44756. this.skeleton.computeAbsoluteTransforms();
  44757. }
  44758. if (this.skeleton.bones[0].length === undefined) {
  44759. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44760. }
  44761. else {
  44762. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44763. }
  44764. if (!this._debugMesh) {
  44765. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44766. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44767. }
  44768. else {
  44769. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44770. }
  44771. this._debugMesh.position.copyFrom(this.mesh.position);
  44772. this._debugMesh.color = this.color;
  44773. };
  44774. SkeletonViewer.prototype.dispose = function () {
  44775. if (this._debugMesh) {
  44776. this.isEnabled = false;
  44777. this._debugMesh.dispose();
  44778. this._debugMesh = null;
  44779. }
  44780. };
  44781. return SkeletonViewer;
  44782. }());
  44783. Debug.SkeletonViewer = SkeletonViewer;
  44784. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44785. })(BABYLON || (BABYLON = {}));
  44786. //# sourceMappingURL=babylon.skeletonViewer.js.map
  44787. var BABYLON;
  44788. (function (BABYLON) {
  44789. var Debug;
  44790. (function (Debug) {
  44791. var AxesViewer = (function () {
  44792. function AxesViewer(scene, scaleLines) {
  44793. if (scaleLines === void 0) { scaleLines = 1; }
  44794. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44795. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44796. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44797. this.scaleLines = 1;
  44798. this.scaleLines = scaleLines;
  44799. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  44800. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  44801. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  44802. this._xmesh.renderingGroupId = 2;
  44803. this._ymesh.renderingGroupId = 2;
  44804. this._zmesh.renderingGroupId = 2;
  44805. this._xmesh.material.checkReadyOnlyOnce = true;
  44806. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  44807. this._ymesh.material.checkReadyOnlyOnce = true;
  44808. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  44809. this._zmesh.material.checkReadyOnlyOnce = true;
  44810. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  44811. this.scene = scene;
  44812. }
  44813. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  44814. var scaleLines = this.scaleLines;
  44815. this._xmesh.position.copyFrom(position);
  44816. this._ymesh.position.copyFrom(position);
  44817. this._zmesh.position.copyFrom(position);
  44818. var point2 = this._xline[1];
  44819. point2.x = xaxis.x * scaleLines;
  44820. point2.y = xaxis.y * scaleLines;
  44821. point2.z = xaxis.z * scaleLines;
  44822. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  44823. point2 = this._yline[1];
  44824. point2.x = yaxis.x * scaleLines;
  44825. point2.y = yaxis.y * scaleLines;
  44826. point2.z = yaxis.z * scaleLines;
  44827. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  44828. point2 = this._zline[1];
  44829. point2.x = zaxis.x * scaleLines;
  44830. point2.y = zaxis.y * scaleLines;
  44831. point2.z = zaxis.z * scaleLines;
  44832. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  44833. };
  44834. AxesViewer.prototype.dispose = function () {
  44835. if (this._xmesh) {
  44836. this._xmesh.dispose();
  44837. this._ymesh.dispose();
  44838. this._zmesh.dispose();
  44839. this._xmesh = null;
  44840. this._ymesh = null;
  44841. this._zmesh = null;
  44842. this._xline = null;
  44843. this._yline = null;
  44844. this._zline = null;
  44845. this.scene = null;
  44846. }
  44847. };
  44848. return AxesViewer;
  44849. }());
  44850. Debug.AxesViewer = AxesViewer;
  44851. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44852. })(BABYLON || (BABYLON = {}));
  44853. //# sourceMappingURL=babylon.axesViewer.js.map
  44854. var BABYLON;
  44855. (function (BABYLON) {
  44856. var Debug;
  44857. (function (Debug) {
  44858. var BoneAxesViewer = (function (_super) {
  44859. __extends(BoneAxesViewer, _super);
  44860. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  44861. if (scaleLines === void 0) { scaleLines = 1; }
  44862. var _this = _super.call(this, scene, scaleLines) || this;
  44863. _this.pos = BABYLON.Vector3.Zero();
  44864. _this.xaxis = BABYLON.Vector3.Zero();
  44865. _this.yaxis = BABYLON.Vector3.Zero();
  44866. _this.zaxis = BABYLON.Vector3.Zero();
  44867. _this.mesh = mesh;
  44868. _this.bone = bone;
  44869. return _this;
  44870. }
  44871. BoneAxesViewer.prototype.update = function () {
  44872. var bone = this.bone;
  44873. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  44874. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  44875. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  44876. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  44877. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  44878. };
  44879. BoneAxesViewer.prototype.dispose = function () {
  44880. if (this.pos) {
  44881. this.pos = null;
  44882. this.xaxis = null;
  44883. this.yaxis = null;
  44884. this.zaxis = null;
  44885. this.mesh = null;
  44886. this.bone = null;
  44887. _super.prototype.dispose.call(this);
  44888. }
  44889. };
  44890. return BoneAxesViewer;
  44891. }(Debug.AxesViewer));
  44892. Debug.BoneAxesViewer = BoneAxesViewer;
  44893. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44894. })(BABYLON || (BABYLON = {}));
  44895. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  44896. var BABYLON;
  44897. (function (BABYLON) {
  44898. var RayHelper = (function () {
  44899. function RayHelper(ray) {
  44900. this.ray = ray;
  44901. }
  44902. RayHelper.CreateAndShow = function (ray, scene, color) {
  44903. var helper = new RayHelper(ray);
  44904. helper.show(scene, color);
  44905. return helper;
  44906. };
  44907. RayHelper.prototype.show = function (scene, color) {
  44908. if (!this._renderFunction) {
  44909. var ray = this.ray;
  44910. this._renderFunction = this._render.bind(this);
  44911. this._scene = scene;
  44912. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  44913. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  44914. this._scene.registerBeforeRender(this._renderFunction);
  44915. }
  44916. if (color) {
  44917. this._renderLine.color.copyFrom(color);
  44918. }
  44919. };
  44920. RayHelper.prototype.hide = function () {
  44921. if (this._renderFunction) {
  44922. this._scene.unregisterBeforeRender(this._renderFunction);
  44923. this._scene = null;
  44924. this._renderFunction = null;
  44925. this._renderLine.dispose();
  44926. this._renderLine = null;
  44927. this._renderPoints = null;
  44928. }
  44929. };
  44930. RayHelper.prototype._render = function () {
  44931. var ray = this.ray;
  44932. var point = this._renderPoints[1];
  44933. var len = Math.min(ray.length, 1000000);
  44934. point.copyFrom(ray.direction);
  44935. point.scaleInPlace(len);
  44936. point.addInPlace(ray.origin);
  44937. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  44938. };
  44939. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  44940. this._attachedToMesh = mesh;
  44941. var ray = this.ray;
  44942. if (!ray.direction) {
  44943. ray.direction = BABYLON.Vector3.Zero();
  44944. }
  44945. if (!ray.origin) {
  44946. ray.origin = BABYLON.Vector3.Zero();
  44947. }
  44948. if (length) {
  44949. ray.length = length;
  44950. }
  44951. if (!meshSpaceOrigin) {
  44952. meshSpaceOrigin = BABYLON.Vector3.Zero();
  44953. }
  44954. if (!meshSpaceDirection) {
  44955. // -1 so that this will work with Mesh.lookAt
  44956. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  44957. }
  44958. if (!this._meshSpaceDirection) {
  44959. this._meshSpaceDirection = meshSpaceDirection.clone();
  44960. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  44961. }
  44962. else {
  44963. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  44964. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  44965. }
  44966. if (!this._updateToMeshFunction) {
  44967. this._updateToMeshFunction = this._updateToMesh.bind(this);
  44968. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  44969. }
  44970. this._updateToMesh();
  44971. };
  44972. RayHelper.prototype.detachFromMesh = function () {
  44973. if (this._attachedToMesh) {
  44974. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  44975. this._attachedToMesh = null;
  44976. this._updateToMeshFunction = null;
  44977. }
  44978. };
  44979. RayHelper.prototype._updateToMesh = function () {
  44980. var ray = this.ray;
  44981. if (this._attachedToMesh._isDisposed) {
  44982. this.detachFromMesh();
  44983. return;
  44984. }
  44985. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  44986. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  44987. };
  44988. RayHelper.prototype.dispose = function () {
  44989. this.hide();
  44990. this.detachFromMesh();
  44991. this.ray = null;
  44992. };
  44993. return RayHelper;
  44994. }());
  44995. BABYLON.RayHelper = RayHelper;
  44996. })(BABYLON || (BABYLON = {}));
  44997. //# sourceMappingURL=babylon.rayHelper.js.map
  44998. var BABYLON;
  44999. (function (BABYLON) {
  45000. var DebugLayer = (function () {
  45001. function DebugLayer(scene) {
  45002. this._scene = scene;
  45003. }
  45004. /** Creates the inspector window. */
  45005. DebugLayer.prototype._createInspector = function (config) {
  45006. if (config === void 0) { config = {}; }
  45007. var popup = config.popup || false;
  45008. var initialTab = config.initialTab || 0;
  45009. var parentElement = config.parentElement || null;
  45010. if (!this._inspector) {
  45011. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  45012. } // else nothing to do,; instance is already existing
  45013. };
  45014. DebugLayer.prototype.isVisible = function () {
  45015. if (!this._inspector) {
  45016. return false;
  45017. }
  45018. return true;
  45019. };
  45020. DebugLayer.prototype.hide = function () {
  45021. if (this._inspector) {
  45022. try {
  45023. this._inspector.dispose();
  45024. }
  45025. catch (e) {
  45026. // If the inspector has been removed directly from the inspector tool
  45027. }
  45028. this._inspector = null;
  45029. }
  45030. };
  45031. DebugLayer.prototype.show = function (config) {
  45032. if (config === void 0) { config = {}; }
  45033. if (typeof INSPECTOR == 'undefined') {
  45034. // Load inspector and add it to the DOM
  45035. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  45036. }
  45037. else {
  45038. // Otherwise creates the inspector
  45039. this._createInspector(config);
  45040. }
  45041. };
  45042. return DebugLayer;
  45043. }());
  45044. // Get protocol used - http or https
  45045. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  45046. BABYLON.DebugLayer = DebugLayer;
  45047. })(BABYLON || (BABYLON = {}));
  45048. //# sourceMappingURL=babylon.debugLayer.js.map
  45049. var BABYLON;
  45050. (function (BABYLON) {
  45051. var Debug;
  45052. (function (Debug) {
  45053. var PhysicsViewer = (function () {
  45054. function PhysicsViewer(scene) {
  45055. this._impostors = [];
  45056. this._meshes = [];
  45057. this._numMeshes = 0;
  45058. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45059. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  45060. }
  45061. PhysicsViewer.prototype._updateDebugMeshes = function () {
  45062. var plugin = this._physicsEnginePlugin;
  45063. for (var i = 0; i < this._numMeshes; i++) {
  45064. if (this._impostors[i].isDisposed) {
  45065. this.hideImpostor(this._impostors[i--]);
  45066. }
  45067. else {
  45068. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  45069. }
  45070. }
  45071. };
  45072. PhysicsViewer.prototype.showImpostor = function (impostor) {
  45073. for (var i = 0; i < this._numMeshes; i++) {
  45074. if (this._impostors[i] == impostor) {
  45075. return;
  45076. }
  45077. }
  45078. var debugMesh = this._physicsEnginePlugin.getDebugMesh(impostor, this._scene);
  45079. if (debugMesh) {
  45080. this._impostors[this._numMeshes] = impostor;
  45081. this._meshes[this._numMeshes] = debugMesh;
  45082. if (this._numMeshes === 0) {
  45083. this._renderFunction = this._updateDebugMeshes.bind(this);
  45084. this._scene.registerBeforeRender(this._renderFunction);
  45085. }
  45086. this._numMeshes++;
  45087. }
  45088. };
  45089. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  45090. var removed = false;
  45091. for (var i = 0; i < this._numMeshes; i++) {
  45092. if (this._impostors[i] == impostor) {
  45093. this._scene.removeMesh(this._meshes[i]);
  45094. this._meshes[i].dispose();
  45095. this._numMeshes--;
  45096. if (this._numMeshes > 0) {
  45097. this._meshes[i] = this._meshes[this._numMeshes];
  45098. this._impostors[i] = this._impostors[this._numMeshes];
  45099. this._meshes[this._numMeshes] = null;
  45100. this._impostors[this._numMeshes] = null;
  45101. }
  45102. else {
  45103. this._meshes[0] = null;
  45104. this._impostors[0] = null;
  45105. }
  45106. removed = true;
  45107. break;
  45108. }
  45109. }
  45110. if (removed && this._numMeshes === 0) {
  45111. this._scene.unregisterBeforeRender(this._renderFunction);
  45112. }
  45113. };
  45114. PhysicsViewer.prototype.dispose = function () {
  45115. for (var i = 0; i < this._numMeshes; i++) {
  45116. this.hideImpostor(this._impostors[i]);
  45117. }
  45118. this._impostors.length = 0;
  45119. this._scene = null;
  45120. this._physicsEnginePlugin = null;
  45121. };
  45122. return PhysicsViewer;
  45123. }());
  45124. Debug.PhysicsViewer = PhysicsViewer;
  45125. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45126. })(BABYLON || (BABYLON = {}));
  45127. //# sourceMappingURL=babylon.physicsViewer.js.map
  45128. var BABYLON;
  45129. (function (BABYLON) {
  45130. var BoundingBoxRenderer = (function () {
  45131. function BoundingBoxRenderer(scene) {
  45132. this.frontColor = new BABYLON.Color3(1, 1, 1);
  45133. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  45134. this.showBackLines = true;
  45135. this.renderList = new BABYLON.SmartArray(32);
  45136. this._vertexBuffers = {};
  45137. this._scene = scene;
  45138. }
  45139. BoundingBoxRenderer.prototype._prepareRessources = function () {
  45140. if (this._colorShader) {
  45141. return;
  45142. }
  45143. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  45144. attributes: [BABYLON.VertexBuffer.PositionKind],
  45145. uniforms: ["world", "viewProjection", "color"]
  45146. });
  45147. var engine = this._scene.getEngine();
  45148. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  45149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  45150. 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]);
  45151. };
  45152. BoundingBoxRenderer.prototype.reset = function () {
  45153. this.renderList.reset();
  45154. };
  45155. BoundingBoxRenderer.prototype.render = function () {
  45156. if (this.renderList.length === 0) {
  45157. return;
  45158. }
  45159. this._prepareRessources();
  45160. if (!this._colorShader.isReady()) {
  45161. return;
  45162. }
  45163. var engine = this._scene.getEngine();
  45164. engine.setDepthWrite(false);
  45165. this._colorShader._preBind();
  45166. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  45167. var boundingBox = this.renderList.data[boundingBoxIndex];
  45168. var min = boundingBox.minimum;
  45169. var max = boundingBox.maximum;
  45170. var diff = max.subtract(min);
  45171. var median = min.add(diff.scale(0.5));
  45172. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  45173. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  45174. .multiply(boundingBox.getWorldMatrix());
  45175. // VBOs
  45176. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  45177. if (this.showBackLines) {
  45178. // Back
  45179. engine.setDepthFunctionToGreaterOrEqual();
  45180. this._scene.resetCachedMaterial();
  45181. this._colorShader.setColor4("color", this.backColor.toColor4());
  45182. this._colorShader.bind(worldMatrix);
  45183. // Draw order
  45184. engine.draw(false, 0, 24);
  45185. }
  45186. // Front
  45187. engine.setDepthFunctionToLess();
  45188. this._scene.resetCachedMaterial();
  45189. this._colorShader.setColor4("color", this.frontColor.toColor4());
  45190. this._colorShader.bind(worldMatrix);
  45191. // Draw order
  45192. engine.draw(false, 0, 24);
  45193. }
  45194. this._colorShader.unbind();
  45195. engine.setDepthFunctionToLessOrEqual();
  45196. engine.setDepthWrite(true);
  45197. };
  45198. BoundingBoxRenderer.prototype.dispose = function () {
  45199. if (!this._colorShader) {
  45200. return;
  45201. }
  45202. this.renderList.dispose();
  45203. this._colorShader.dispose();
  45204. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45205. if (buffer) {
  45206. buffer.dispose();
  45207. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45208. }
  45209. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45210. };
  45211. return BoundingBoxRenderer;
  45212. }());
  45213. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  45214. })(BABYLON || (BABYLON = {}));
  45215. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  45216. var BABYLON;
  45217. (function (BABYLON) {
  45218. var TextureTools = (function () {
  45219. function TextureTools() {
  45220. }
  45221. /**
  45222. * Uses the GPU to create a copy texture rescaled at a given size
  45223. * @param texture Texture to copy from
  45224. * @param width Desired width
  45225. * @param height Desired height
  45226. * @return Generated texture
  45227. */
  45228. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  45229. if (useBilinearMode === void 0) { useBilinearMode = true; }
  45230. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  45231. var scene = texture.getScene();
  45232. var engine = scene.getEngine();
  45233. rtt.wrapU = texture.wrapU;
  45234. rtt.wrapV = texture.wrapV;
  45235. rtt.uOffset = texture.uOffset;
  45236. rtt.vOffset = texture.vOffset;
  45237. rtt.uScale = texture.uScale;
  45238. rtt.vScale = texture.vScale;
  45239. rtt.uAng = texture.uAng;
  45240. rtt.vAng = texture.vAng;
  45241. rtt.wAng = texture.wAng;
  45242. rtt.coordinatesIndex = texture.coordinatesIndex;
  45243. rtt.level = texture.level;
  45244. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  45245. rtt._texture.isReady = false;
  45246. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45247. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45248. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45249. passPostProcess.getEffect().executeWhenCompiled(function () {
  45250. passPostProcess.onApply = function (effect) {
  45251. effect.setTexture("textureSampler", texture);
  45252. };
  45253. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  45254. engine.unBindFramebuffer(rtt.getInternalTexture());
  45255. rtt.disposeFramebufferObjects();
  45256. passPostProcess.dispose();
  45257. rtt._texture.isReady = true;
  45258. });
  45259. return rtt;
  45260. };
  45261. return TextureTools;
  45262. }());
  45263. BABYLON.TextureTools = TextureTools;
  45264. })(BABYLON || (BABYLON = {}));
  45265. //# sourceMappingURL=babylon.textureTools.js.map
  45266. var BABYLON;
  45267. (function (BABYLON) {
  45268. var Internals;
  45269. (function (Internals) {
  45270. var FileFaceOrientation = (function () {
  45271. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45272. this.name = name;
  45273. this.worldAxisForNormal = worldAxisForNormal;
  45274. this.worldAxisForFileX = worldAxisForFileX;
  45275. this.worldAxisForFileY = worldAxisForFileY;
  45276. }
  45277. return FileFaceOrientation;
  45278. }());
  45279. ;
  45280. /**
  45281. * Helper class dealing with the extraction of spherical polynomial dataArray
  45282. * from a cube map.
  45283. */
  45284. var CubeMapToSphericalPolynomialTools = (function () {
  45285. function CubeMapToSphericalPolynomialTools() {
  45286. }
  45287. /**
  45288. * Converts a cubemap to the according Spherical Polynomial data.
  45289. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45290. *
  45291. * @param cubeInfo The Cube map to extract the information from.
  45292. * @return The Spherical Polynomial data.
  45293. */
  45294. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45295. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45296. var totalSolidAngle = 0.0;
  45297. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45298. var du = 2.0 / cubeInfo.size;
  45299. var dv = du;
  45300. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45301. var minUV = du * 0.5 - 1.0;
  45302. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45303. var fileFace = this.FileFaces[faceIndex];
  45304. var dataArray = cubeInfo[fileFace.name];
  45305. var v = minUV;
  45306. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45307. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45308. // Because SP is still linear, so summation is fine in that basis.
  45309. for (var y = 0; y < cubeInfo.size; y++) {
  45310. var u = minUV;
  45311. for (var x = 0; x < cubeInfo.size; x++) {
  45312. // World direction (not normalised)
  45313. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45314. worldDirection.normalize();
  45315. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45316. if (1) {
  45317. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  45318. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  45319. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  45320. var color = new BABYLON.Color3(r, g, b);
  45321. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45322. }
  45323. else {
  45324. if (faceIndex == 0) {
  45325. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45326. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45327. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45328. }
  45329. else if (faceIndex == 1) {
  45330. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45331. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45332. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45333. }
  45334. else if (faceIndex == 2) {
  45335. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45336. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45337. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45338. }
  45339. else if (faceIndex == 3) {
  45340. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45341. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45342. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45343. }
  45344. else if (faceIndex == 4) {
  45345. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45346. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45347. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45348. }
  45349. else if (faceIndex == 5) {
  45350. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45351. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45352. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45353. }
  45354. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  45355. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45356. }
  45357. totalSolidAngle += deltaSolidAngle;
  45358. u += du;
  45359. }
  45360. v += dv;
  45361. }
  45362. }
  45363. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  45364. var correction = correctSolidAngle / totalSolidAngle;
  45365. sphericalHarmonics.scale(correction);
  45366. // Additionally scale by pi -- audit needed
  45367. sphericalHarmonics.scale(1.0 / Math.PI);
  45368. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  45369. };
  45370. return CubeMapToSphericalPolynomialTools;
  45371. }());
  45372. CubeMapToSphericalPolynomialTools.FileFaces = [
  45373. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45374. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45375. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45376. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45377. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45378. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45379. ];
  45380. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45381. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45382. })(BABYLON || (BABYLON = {}));
  45383. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45384. var BABYLON;
  45385. (function (BABYLON) {
  45386. var Internals;
  45387. (function (Internals) {
  45388. /**
  45389. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  45390. */
  45391. var PanoramaToCubeMapTools = (function () {
  45392. function PanoramaToCubeMapTools() {
  45393. }
  45394. /**
  45395. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  45396. *
  45397. * @param float32Array The source data.
  45398. * @param inputWidth The width of the input panorama.
  45399. * @param inputhHeight The height of the input panorama.
  45400. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  45401. * @return The cubemap data
  45402. */
  45403. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  45404. if (!float32Array) {
  45405. throw "ConvertPanoramaToCubemap: input cannot be null";
  45406. }
  45407. if (float32Array.length != inputWidth * inputHeight * 3) {
  45408. throw "ConvertPanoramaToCubemap: input size is wrong";
  45409. }
  45410. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  45411. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  45412. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  45413. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  45414. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  45415. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  45416. return {
  45417. front: textureFront,
  45418. back: textureBack,
  45419. left: textureLeft,
  45420. right: textureRight,
  45421. up: textureUp,
  45422. down: textureDown,
  45423. size: size
  45424. };
  45425. };
  45426. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  45427. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  45428. var textureArray = new Float32Array(buffer);
  45429. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  45430. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  45431. var dy = 1 / texSize;
  45432. var fy = 0;
  45433. for (var y = 0; y < texSize; y++) {
  45434. var xv1 = faceData[0];
  45435. var xv2 = faceData[2];
  45436. for (var x = 0; x < texSize; x++) {
  45437. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  45438. v.normalize();
  45439. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  45440. // 3 channels per pixels
  45441. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  45442. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  45443. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  45444. xv1 = xv1.add(rotDX1);
  45445. xv2 = xv2.add(rotDX2);
  45446. }
  45447. fy += dy;
  45448. }
  45449. return textureArray;
  45450. };
  45451. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  45452. var theta = Math.atan2(vDir.z, vDir.x);
  45453. var phi = Math.acos(vDir.y);
  45454. while (theta < -Math.PI)
  45455. theta += 2 * Math.PI;
  45456. while (theta > Math.PI)
  45457. theta -= 2 * Math.PI;
  45458. var dx = theta / Math.PI;
  45459. var dy = phi / Math.PI;
  45460. // recenter.
  45461. dx = dx * 0.5 + 0.5;
  45462. var px = Math.round(dx * inputWidth);
  45463. if (px < 0)
  45464. px = 0;
  45465. else if (px >= inputWidth)
  45466. px = inputWidth - 1;
  45467. var py = Math.round(dy * inputHeight);
  45468. if (py < 0)
  45469. py = 0;
  45470. else if (py >= inputHeight)
  45471. py = inputHeight - 1;
  45472. var inputY = (inputHeight - py - 1);
  45473. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  45474. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  45475. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  45476. return {
  45477. r: r,
  45478. g: g,
  45479. b: b
  45480. };
  45481. };
  45482. return PanoramaToCubeMapTools;
  45483. }());
  45484. PanoramaToCubeMapTools.FACE_FRONT = [
  45485. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45486. new BABYLON.Vector3(1.0, -1.0, -1.0),
  45487. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  45488. new BABYLON.Vector3(1.0, 1.0, -1.0)
  45489. ];
  45490. PanoramaToCubeMapTools.FACE_BACK = [
  45491. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45492. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45493. new BABYLON.Vector3(1.0, 1.0, 1.0),
  45494. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  45495. ];
  45496. PanoramaToCubeMapTools.FACE_RIGHT = [
  45497. new BABYLON.Vector3(1.0, -1.0, -1.0),
  45498. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45499. new BABYLON.Vector3(1.0, 1.0, -1.0),
  45500. new BABYLON.Vector3(1.0, 1.0, 1.0)
  45501. ];
  45502. PanoramaToCubeMapTools.FACE_LEFT = [
  45503. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45504. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45505. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  45506. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  45507. ];
  45508. PanoramaToCubeMapTools.FACE_DOWN = [
  45509. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  45510. new BABYLON.Vector3(1.0, 1.0, -1.0),
  45511. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  45512. new BABYLON.Vector3(1.0, 1.0, 1.0)
  45513. ];
  45514. PanoramaToCubeMapTools.FACE_UP = [
  45515. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45516. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45517. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45518. new BABYLON.Vector3(1.0, -1.0, -1.0)
  45519. ];
  45520. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  45521. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45522. })(BABYLON || (BABYLON = {}));
  45523. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  45524. var BABYLON;
  45525. (function (BABYLON) {
  45526. var Internals;
  45527. (function (Internals) {
  45528. ;
  45529. /**
  45530. * This groups tools to convert HDR texture to native colors array.
  45531. */
  45532. var HDRTools = (function () {
  45533. function HDRTools() {
  45534. }
  45535. HDRTools.Ldexp = function (mantissa, exponent) {
  45536. if (exponent > 1023) {
  45537. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  45538. }
  45539. if (exponent < -1074) {
  45540. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  45541. }
  45542. return mantissa * Math.pow(2, exponent);
  45543. };
  45544. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  45545. if (exponent > 0) {
  45546. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  45547. float32array[index + 0] = red * exponent;
  45548. float32array[index + 1] = green * exponent;
  45549. float32array[index + 2] = blue * exponent;
  45550. }
  45551. else {
  45552. float32array[index + 0] = 0;
  45553. float32array[index + 1] = 0;
  45554. float32array[index + 2] = 0;
  45555. }
  45556. };
  45557. HDRTools.readStringLine = function (uint8array, startIndex) {
  45558. var line = "";
  45559. var character = "";
  45560. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  45561. character = String.fromCharCode(uint8array[i]);
  45562. if (character == "\n") {
  45563. break;
  45564. }
  45565. line += character;
  45566. }
  45567. return line;
  45568. };
  45569. /**
  45570. * Reads header information from an RGBE texture stored in a native array.
  45571. * More information on this format are available here:
  45572. * https://en.wikipedia.org/wiki/RGBE_image_format
  45573. *
  45574. * @param uint8array The binary file stored in native array.
  45575. * @return The header information.
  45576. */
  45577. HDRTools.RGBE_ReadHeader = function (uint8array) {
  45578. var height = 0;
  45579. var width = 0;
  45580. var line = this.readStringLine(uint8array, 0);
  45581. if (line[0] != '#' || line[1] != '?') {
  45582. throw "Bad HDR Format.";
  45583. }
  45584. var endOfHeader = false;
  45585. var findFormat = false;
  45586. var lineIndex = 0;
  45587. do {
  45588. lineIndex += (line.length + 1);
  45589. line = this.readStringLine(uint8array, lineIndex);
  45590. if (line == "FORMAT=32-bit_rle_rgbe") {
  45591. findFormat = true;
  45592. }
  45593. else if (line.length == 0) {
  45594. endOfHeader = true;
  45595. }
  45596. } while (!endOfHeader);
  45597. if (!findFormat) {
  45598. throw "HDR Bad header format, unsupported FORMAT";
  45599. }
  45600. lineIndex += (line.length + 1);
  45601. line = this.readStringLine(uint8array, lineIndex);
  45602. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  45603. var match = sizeRegexp.exec(line);
  45604. // TODO. Support +Y and -X if needed.
  45605. if (match.length < 3) {
  45606. throw "HDR Bad header format, no size";
  45607. }
  45608. width = parseInt(match[2]);
  45609. height = parseInt(match[1]);
  45610. if (width < 8 || width > 0x7fff) {
  45611. throw "HDR Bad header format, unsupported size";
  45612. }
  45613. lineIndex += (line.length + 1);
  45614. return {
  45615. height: height,
  45616. width: width,
  45617. dataPosition: lineIndex
  45618. };
  45619. };
  45620. /**
  45621. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  45622. * This RGBE texture needs to store the information as a panorama.
  45623. *
  45624. * More information on this format are available here:
  45625. * https://en.wikipedia.org/wiki/RGBE_image_format
  45626. *
  45627. * @param buffer The binary file stored in an array buffer.
  45628. * @param size The expected size of the extracted cubemap.
  45629. * @return The Cube Map information.
  45630. */
  45631. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  45632. var uint8array = new Uint8Array(buffer);
  45633. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  45634. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  45635. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  45636. return cubeMapData;
  45637. };
  45638. /**
  45639. * Returns the pixels data extracted from an RGBE texture.
  45640. * This pixels will be stored left to right up to down in the R G B order in one array.
  45641. *
  45642. * More information on this format are available here:
  45643. * https://en.wikipedia.org/wiki/RGBE_image_format
  45644. *
  45645. * @param uint8array The binary file stored in an array buffer.
  45646. * @param hdrInfo The header information of the file.
  45647. * @return The pixels data in RGB right to left up to down order.
  45648. */
  45649. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  45650. // Keep for multi format supports.
  45651. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  45652. };
  45653. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  45654. var num_scanlines = hdrInfo.height;
  45655. var scanline_width = hdrInfo.width;
  45656. var a, b, c, d, count;
  45657. var dataIndex = hdrInfo.dataPosition;
  45658. var index = 0, endIndex = 0, i = 0;
  45659. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  45660. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  45661. // 3 channels of 4 bytes per pixel in float.
  45662. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  45663. var resultArray = new Float32Array(resultBuffer);
  45664. // read in each successive scanline
  45665. while (num_scanlines > 0) {
  45666. a = uint8array[dataIndex++];
  45667. b = uint8array[dataIndex++];
  45668. c = uint8array[dataIndex++];
  45669. d = uint8array[dataIndex++];
  45670. if (a != 2 || b != 2 || (c & 0x80)) {
  45671. // this file is not run length encoded
  45672. throw "HDR Bad header format, not RLE";
  45673. }
  45674. if (((c << 8) | d) != scanline_width) {
  45675. throw "HDR Bad header format, wrong scan line width";
  45676. }
  45677. index = 0;
  45678. // read each of the four channels for the scanline into the buffer
  45679. for (i = 0; i < 4; i++) {
  45680. endIndex = (i + 1) * scanline_width;
  45681. while (index < endIndex) {
  45682. a = uint8array[dataIndex++];
  45683. b = uint8array[dataIndex++];
  45684. if (a > 128) {
  45685. // a run of the same value
  45686. count = a - 128;
  45687. if ((count == 0) || (count > endIndex - index)) {
  45688. throw "HDR Bad Format, bad scanline data (run)";
  45689. }
  45690. while (count-- > 0) {
  45691. scanLineArray[index++] = b;
  45692. }
  45693. }
  45694. else {
  45695. // a non-run
  45696. count = a;
  45697. if ((count == 0) || (count > endIndex - index)) {
  45698. throw "HDR Bad Format, bad scanline data (non-run)";
  45699. }
  45700. scanLineArray[index++] = b;
  45701. if (--count > 0) {
  45702. for (var j = 0; j < count; j++) {
  45703. scanLineArray[index++] = uint8array[dataIndex++];
  45704. }
  45705. }
  45706. }
  45707. }
  45708. }
  45709. // now convert data from buffer into floats
  45710. for (i = 0; i < scanline_width; i++) {
  45711. a = scanLineArray[i];
  45712. b = scanLineArray[i + scanline_width];
  45713. c = scanLineArray[i + 2 * scanline_width];
  45714. d = scanLineArray[i + 3 * scanline_width];
  45715. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  45716. }
  45717. num_scanlines--;
  45718. }
  45719. return resultArray;
  45720. };
  45721. return HDRTools;
  45722. }());
  45723. Internals.HDRTools = HDRTools;
  45724. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45725. })(BABYLON || (BABYLON = {}));
  45726. //# sourceMappingURL=babylon.hdr.js.map
  45727. //_______________________________________________________________
  45728. // Extracted from CubeMapGen:
  45729. // https://code.google.com/archive/p/cubemapgen/
  45730. //
  45731. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  45732. //_______________________________________________________________
  45733. var BABYLON;
  45734. (function (BABYLON) {
  45735. var Internals;
  45736. (function (Internals) {
  45737. /**
  45738. * The bounding box information used during the conversion process.
  45739. */
  45740. var CMGBoundinBox = (function () {
  45741. function CMGBoundinBox() {
  45742. this.min = new BABYLON.Vector3(0, 0, 0);
  45743. this.max = new BABYLON.Vector3(0, 0, 0);
  45744. this.clear();
  45745. }
  45746. CMGBoundinBox.prototype.clear = function () {
  45747. this.min.x = CMGBoundinBox.MAX;
  45748. this.min.y = CMGBoundinBox.MAX;
  45749. this.min.z = CMGBoundinBox.MAX;
  45750. this.max.x = CMGBoundinBox.MIN;
  45751. this.max.y = CMGBoundinBox.MIN;
  45752. this.max.z = CMGBoundinBox.MIN;
  45753. };
  45754. CMGBoundinBox.prototype.augment = function (x, y, z) {
  45755. this.min.x = Math.min(this.min.x, x);
  45756. this.min.y = Math.min(this.min.y, y);
  45757. this.min.z = Math.min(this.min.z, z);
  45758. this.max.x = Math.max(this.max.x, x);
  45759. this.max.y = Math.max(this.max.y, y);
  45760. this.max.z = Math.max(this.max.z, z);
  45761. };
  45762. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  45763. this.min.x = Math.max(this.min.x, x);
  45764. this.min.y = Math.max(this.min.y, y);
  45765. this.min.z = Math.max(this.min.z, z);
  45766. };
  45767. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  45768. this.max.x = Math.min(this.max.x, x);
  45769. this.max.y = Math.min(this.max.y, y);
  45770. this.max.z = Math.min(this.max.z, z);
  45771. };
  45772. CMGBoundinBox.prototype.empty = function () {
  45773. if ((this.min.x > this.max.y) ||
  45774. (this.min.y > this.max.y) ||
  45775. (this.min.z > this.max.y)) {
  45776. return true;
  45777. }
  45778. else {
  45779. return false;
  45780. }
  45781. };
  45782. return CMGBoundinBox;
  45783. }());
  45784. CMGBoundinBox.MAX = Number.MAX_VALUE;
  45785. CMGBoundinBox.MIN = Number.MIN_VALUE;
  45786. /**
  45787. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  45788. * required by the glossinees of a material.
  45789. *
  45790. * This only supports the cosine drop power as well as Warp fixup generation method.
  45791. *
  45792. * This is using the process from CubeMapGen described here:
  45793. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  45794. */
  45795. var PMREMGenerator = (function () {
  45796. /**
  45797. * Constructor of the generator.
  45798. *
  45799. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  45800. * @param inputSize The size of the cubemap faces
  45801. * @param outputSize The size of the output cubemap faces
  45802. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  45803. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  45804. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  45805. * @param specularPower The max specular level of the desired cubemap
  45806. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  45807. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  45808. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  45809. */
  45810. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  45811. this.input = input;
  45812. this.inputSize = inputSize;
  45813. this.outputSize = outputSize;
  45814. this.maxNumMipLevels = maxNumMipLevels;
  45815. this.numChannels = numChannels;
  45816. this.isFloat = isFloat;
  45817. this.specularPower = specularPower;
  45818. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  45819. this.excludeBase = excludeBase;
  45820. this.fixup = fixup;
  45821. this._outputSurface = [];
  45822. this._numMipLevels = 0;
  45823. }
  45824. /**
  45825. * Launches the filter process and return the result.
  45826. *
  45827. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  45828. */
  45829. PMREMGenerator.prototype.filterCubeMap = function () {
  45830. // Init cubemap processor
  45831. this.init();
  45832. // Filters the cubemap
  45833. this.filterCubeMapMipChain();
  45834. // Returns the filtered mips.
  45835. return this._outputSurface;
  45836. };
  45837. PMREMGenerator.prototype.init = function () {
  45838. var i;
  45839. var j;
  45840. var mipLevelSize;
  45841. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  45842. if (this.maxNumMipLevels == 0) {
  45843. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  45844. }
  45845. //first miplevel size
  45846. mipLevelSize = this.outputSize;
  45847. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  45848. for (j = 0; j < this.maxNumMipLevels; j++) {
  45849. this._outputSurface.length++;
  45850. this._outputSurface[j] = [];
  45851. //Iterate over faces for output images
  45852. for (i = 0; i < 6; i++) {
  45853. this._outputSurface[j].length++;
  45854. // Initializes a new array for the output.
  45855. if (this.isFloat) {
  45856. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  45857. }
  45858. else {
  45859. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  45860. }
  45861. }
  45862. //next mip level is half size
  45863. mipLevelSize >>= 1;
  45864. this._numMipLevels++;
  45865. //terminate if mip chain becomes too small
  45866. if (mipLevelSize == 0) {
  45867. this.maxNumMipLevels = j;
  45868. return;
  45869. }
  45870. }
  45871. };
  45872. //--------------------------------------------------------------------------------------
  45873. //Cube map filtering and mip chain generation.
  45874. // the cube map filtereing is specified using a number of parameters:
  45875. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  45876. // indicates the region of the hemisphere to filter over for each tap.
  45877. //
  45878. // Note that the top mip level is also a filtered version of the original input images
  45879. // as well in order to create mip chains for diffuse environment illumination.
  45880. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  45881. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  45882. //
  45883. // Then the mip angle used to genreate the next level of the mip chain from the first level
  45884. // is a_InitialMipAngle
  45885. //
  45886. // The angle for the subsequent levels of the mip chain are specified by their parents
  45887. // filtering angle and a per-level scale and bias
  45888. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  45889. //
  45890. //--------------------------------------------------------------------------------------
  45891. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  45892. // First, take count of the lighting model to modify SpecularPower
  45893. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  45894. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  45895. //Cone angle start (for generating subsequent mip levels)
  45896. var currentSpecularPower = this.specularPower;
  45897. //Build filter lookup tables based on the source miplevel size
  45898. this.precomputeFilterLookupTables(this.inputSize);
  45899. // Note that we need to filter the first level before generating mipmap
  45900. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  45901. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  45902. // TODO : Write a function to copy and scale the base mipmap in output
  45903. // I am just lazy here and just put a high specular power value, and do some if.
  45904. if (this.excludeBase && (levelIndex == 0)) {
  45905. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  45906. currentSpecularPower = 100000.0;
  45907. }
  45908. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  45909. var srcCubeImage = this.input;
  45910. var dstCubeImage = this._outputSurface[levelIndex];
  45911. var dstSize = this.outputSize >> levelIndex;
  45912. // Compute required angle.
  45913. var angle = this.getBaseFilterAngle(currentSpecularPower);
  45914. // filter cube surfaces
  45915. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  45916. // fix seams
  45917. if (this.fixup) {
  45918. this.fixupCubeEdges(dstCubeImage, dstSize);
  45919. }
  45920. // Decrease the specular power to generate the mipmap chain
  45921. // TODO : Use another method for Exclude (see first comment at start of the function
  45922. if (this.excludeBase && (levelIndex == 0)) {
  45923. currentSpecularPower = this.specularPower;
  45924. }
  45925. currentSpecularPower *= this.cosinePowerDropPerMip;
  45926. }
  45927. };
  45928. //--------------------------------------------------------------------------------------
  45929. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  45930. // It allow to optimize the texel to access base on the specular power.
  45931. //--------------------------------------------------------------------------------------
  45932. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  45933. // We want to find the alpha such that:
  45934. // cos(alpha)^cosinePower = epsilon
  45935. // That's: acos(epsilon^(1/cosinePower))
  45936. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  45937. var angle = 180.0;
  45938. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  45939. angle *= 180.0 / Math.PI; // Convert to degree
  45940. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  45941. return angle;
  45942. };
  45943. //--------------------------------------------------------------------------------------
  45944. //Builds the following lookup tables prior to filtering:
  45945. // -normalizer cube map
  45946. // -tap weight lookup table
  45947. //
  45948. //--------------------------------------------------------------------------------------
  45949. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  45950. var srcTexelAngle;
  45951. var iCubeFace;
  45952. //clear pre-existing normalizer cube map
  45953. this._normCubeMap = [];
  45954. //Normalized vectors per cubeface and per-texel solid angle
  45955. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  45956. };
  45957. //--------------------------------------------------------------------------------------
  45958. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  45959. //
  45960. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  45961. //
  45962. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  45963. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  45964. // below
  45965. //--------------------------------------------------------------------------------------
  45966. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  45967. var iCubeFace;
  45968. var u;
  45969. var v;
  45970. //iterate over cube faces
  45971. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  45972. //First three channels for norm cube, and last channel for solid angle
  45973. this._normCubeMap.push(new Float32Array(size * size * 4));
  45974. //fast texture walk, build normalizer cube map
  45975. var facesData = this.input[iCubeFace];
  45976. for (v = 0; v < size; v++) {
  45977. for (u = 0; u < size; u++) {
  45978. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  45979. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  45980. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  45981. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  45982. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  45983. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  45984. }
  45985. }
  45986. }
  45987. };
  45988. //--------------------------------------------------------------------------------------
  45989. // Convert cubemap face texel coordinates and face idx to 3D vector
  45990. // note the U and V coords are integer coords and range from 0 to size-1
  45991. // this routine can be used to generate a normalizer cube map
  45992. //--------------------------------------------------------------------------------------
  45993. // SL BEGIN
  45994. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  45995. var nvcU;
  45996. var nvcV;
  45997. var tempVec;
  45998. // Change from original AMD code
  45999. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  46000. // + 0.5f is for texel center addressing
  46001. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  46002. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  46003. // warp fixup
  46004. if (fixup && size > 1) {
  46005. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  46006. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  46007. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  46008. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  46009. }
  46010. // Get current vector
  46011. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  46012. // U contribution
  46013. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  46014. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  46015. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  46016. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  46017. // V contribution and Sum
  46018. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  46019. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  46020. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  46021. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  46022. //add face axis
  46023. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  46024. PMREMGenerator._vectorTemp.x += faceAxis[0];
  46025. PMREMGenerator._vectorTemp.y += faceAxis[1];
  46026. PMREMGenerator._vectorTemp.z += faceAxis[2];
  46027. //normalize vector
  46028. PMREMGenerator._vectorTemp.normalize();
  46029. return PMREMGenerator._vectorTemp;
  46030. };
  46031. //--------------------------------------------------------------------------------------
  46032. // Convert 3D vector to cubemap face texel coordinates and face idx
  46033. // note the U and V coords are integer coords and range from 0 to size-1
  46034. // this routine can be used to generate a normalizer cube map
  46035. //
  46036. // returns face IDX and texel coords
  46037. //--------------------------------------------------------------------------------------
  46038. // SL BEGIN
  46039. /*
  46040. Mapping Texture Coordinates to Cube Map Faces
  46041. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  46042. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  46043. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  46044. map arrangement in Pixar's RenderMan package.
  46045. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  46046. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  46047. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  46048. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  46049. the major axis direction). The target column in the table below explains how the major axis direction
  46050. maps to the 2D image of a particular cube map target.
  46051. major axis
  46052. direction target sc tc ma
  46053. ---------- --------------------------------- --- --- ---
  46054. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  46055. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  46056. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  46057. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  46058. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  46059. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  46060. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  46061. an updated (s,t) is calculated as follows
  46062. s = ( sc/|ma| + 1 ) / 2
  46063. t = ( tc/|ma| + 1 ) / 2
  46064. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  46065. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  46066. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  46067. */
  46068. // Note this method return U and V in range from 0 to size-1
  46069. // SL END
  46070. // Store the information in vector3 for convenience (faceindex, u, v)
  46071. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  46072. var maxCoord;
  46073. var faceIdx;
  46074. //absolute value 3
  46075. var absX = Math.abs(x);
  46076. var absY = Math.abs(y);
  46077. var absZ = Math.abs(z);
  46078. if (absX >= absY && absX >= absZ) {
  46079. maxCoord = absX;
  46080. if (x >= 0) {
  46081. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  46082. }
  46083. else {
  46084. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  46085. }
  46086. }
  46087. else if (absY >= absX && absY >= absZ) {
  46088. maxCoord = absY;
  46089. if (y >= 0) {
  46090. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  46091. }
  46092. else {
  46093. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  46094. }
  46095. }
  46096. else {
  46097. maxCoord = absZ;
  46098. if (z >= 0) {
  46099. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  46100. }
  46101. else {
  46102. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  46103. }
  46104. }
  46105. //divide through by max coord so face vector lies on cube face
  46106. var scale = 1 / maxCoord;
  46107. x *= scale;
  46108. y *= scale;
  46109. z *= scale;
  46110. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  46111. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  46112. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  46113. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  46114. // Modify original AMD code to return value from 0 to Size - 1
  46115. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  46116. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  46117. PMREMGenerator._vectorTemp.x = faceIdx;
  46118. PMREMGenerator._vectorTemp.y = u;
  46119. PMREMGenerator._vectorTemp.z = v;
  46120. return PMREMGenerator._vectorTemp;
  46121. };
  46122. //--------------------------------------------------------------------------------------
  46123. //Original code from Ignacio CastaÒo
  46124. // This formula is from Manne ÷hrstrˆm's thesis.
  46125. // Take two coordiantes in the range [-1, 1] that define a portion of a
  46126. // cube face and return the area of the projection of that portion on the
  46127. // surface of the sphere.
  46128. //--------------------------------------------------------------------------------------
  46129. PMREMGenerator.prototype.areaElement = function (x, y) {
  46130. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  46131. };
  46132. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  46133. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  46134. // (+ 0.5f is for texel center addressing)
  46135. u = (2.0 * (u + 0.5) / size) - 1.0;
  46136. v = (2.0 * (v + 0.5) / size) - 1.0;
  46137. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  46138. var invResolution = 1.0 / size;
  46139. // U and V are the -1..1 texture coordinate on the current face.
  46140. // Get projected area for this texel
  46141. var x0 = u - invResolution;
  46142. var y0 = v - invResolution;
  46143. var x1 = u + invResolution;
  46144. var y1 = v + invResolution;
  46145. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  46146. return solidAngle;
  46147. };
  46148. //--------------------------------------------------------------------------------------
  46149. //The key to the speed of these filtering routines is to quickly define a per-face
  46150. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  46151. // Later these pixels are selectively processed based on their dot products to see if
  46152. // they reside within the filtering cone.
  46153. //
  46154. //This is done by computing the smallest per-texel angle to get a conservative estimate
  46155. // of the number of texels needed to be covered in width and height order to filter the
  46156. // region. the bounding box for the center taps face is defined first, and if the
  46157. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  46158. // defined next
  46159. //--------------------------------------------------------------------------------------
  46160. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  46161. // note that pixels within these regions may be rejected
  46162. // based on the anlge
  46163. var iCubeFace;
  46164. var u;
  46165. var v;
  46166. // bounding box per face to specify region to process
  46167. var filterExtents = [];
  46168. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  46169. filterExtents.push(new CMGBoundinBox());
  46170. }
  46171. // min angle a src texel can cover (in degrees)
  46172. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  46173. // angle about center tap to define filter cone
  46174. // filter angle is 1/2 the cone angle
  46175. var filterAngle = filterConeAngle / 2.0;
  46176. //ensure filter angle is larger than a texel
  46177. if (filterAngle < srcTexelAngle) {
  46178. filterAngle = srcTexelAngle;
  46179. }
  46180. //ensure filter cone is always smaller than the hemisphere
  46181. if (filterAngle > 90.0) {
  46182. filterAngle = 90.0;
  46183. }
  46184. // the maximum number of texels in 1D the filter cone angle will cover
  46185. // used to determine bounding box size for filter extents
  46186. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  46187. // ensure conservative region always covers at least one texel
  46188. if (filterSize < 1) {
  46189. filterSize = 1;
  46190. }
  46191. // dotProdThresh threshold based on cone angle to determine whether or not taps
  46192. // reside within the cone angle
  46193. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  46194. // process required faces
  46195. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  46196. //iterate over dst cube map face texel
  46197. for (v = 0; v < dstSize; v++) {
  46198. for (u = 0; u < dstSize; u++) {
  46199. //get center tap direction
  46200. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  46201. //clear old per-face filter extents
  46202. this.clearFilterExtents(filterExtents);
  46203. //define per-face filter extents
  46204. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  46205. //perform filtering of src faces using filter extents
  46206. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  46207. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  46208. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  46209. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  46210. }
  46211. }
  46212. }
  46213. };
  46214. //--------------------------------------------------------------------------------------
  46215. //Clear filter extents for the 6 cube map faces
  46216. //--------------------------------------------------------------------------------------
  46217. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  46218. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  46219. filterExtents[iCubeFaces].clear();
  46220. }
  46221. };
  46222. //--------------------------------------------------------------------------------------
  46223. //Define per-face bounding box filter extents
  46224. //
  46225. // These define conservative texel regions in each of the faces the filter can possibly
  46226. // process. When the pixels in the regions are actually processed, the dot product
  46227. // between the tap vector and the center tap vector is used to determine the weight of
  46228. // the tap and whether or not the tap is within the cone.
  46229. //
  46230. //--------------------------------------------------------------------------------------
  46231. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  46232. //neighboring face and bleed over amount, and width of BBOX for
  46233. // left, right, top, and bottom edges of this face
  46234. var bleedOverAmount = [0, 0, 0, 0];
  46235. var bleedOverBBoxMin = [0, 0, 0, 0];
  46236. var bleedOverBBoxMax = [0, 0, 0, 0];
  46237. var neighborFace;
  46238. var neighborEdge;
  46239. var oppositeFaceIdx;
  46240. //get face idx, and u, v info from center tap dir
  46241. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  46242. var faceIdx = result.x;
  46243. var u = result.y;
  46244. var v = result.z;
  46245. //define bbox size within face
  46246. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  46247. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  46248. filterExtents[faceIdx].clampMin(0, 0, 0);
  46249. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  46250. //u and v extent in face corresponding to center tap
  46251. var minU = filterExtents[faceIdx].min.x;
  46252. var minV = filterExtents[faceIdx].min.y;
  46253. var maxU = filterExtents[faceIdx].max.x;
  46254. var maxV = filterExtents[faceIdx].max.y;
  46255. //bleed over amounts for face across u=0 edge (left)
  46256. bleedOverAmount[0] = (bboxSize - u);
  46257. bleedOverBBoxMin[0] = minV;
  46258. bleedOverBBoxMax[0] = maxV;
  46259. //bleed over amounts for face across u=1 edge (right)
  46260. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  46261. bleedOverBBoxMin[1] = minV;
  46262. bleedOverBBoxMax[1] = maxV;
  46263. //bleed over to face across v=0 edge (up)
  46264. bleedOverAmount[2] = (bboxSize - v);
  46265. bleedOverBBoxMin[2] = minU;
  46266. bleedOverBBoxMax[2] = maxU;
  46267. //bleed over to face across v=1 edge (down)
  46268. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  46269. bleedOverBBoxMin[3] = minU;
  46270. bleedOverBBoxMax[3] = maxU;
  46271. //compute bleed over regions in neighboring faces
  46272. for (var i = 0; i < 4; i++) {
  46273. if (bleedOverAmount[i] > 0) {
  46274. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  46275. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  46276. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  46277. // be flipped: the cases are
  46278. // if a left edge mates with a left or bottom edge on the neighbor
  46279. // if a top edge mates with a top or right edge on the neighbor
  46280. // if a right edge mates with a right or top edge on the neighbor
  46281. // if a bottom edge mates with a bottom or left edge on the neighbor
  46282. //Seeing as the edges are enumerated as follows
  46283. // left =0
  46284. // right =1
  46285. // top =2
  46286. // bottom =3
  46287. //
  46288. // so if the edge enums are the same, or the sum of the enums == 3,
  46289. // the bbox needs to be flipped
  46290. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  46291. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  46292. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  46293. }
  46294. //The way the bounding box is extended onto the neighboring face
  46295. // depends on which edge of neighboring face abuts with this one
  46296. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  46297. case PMREMGenerator.CP_EDGE_LEFT:
  46298. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  46299. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  46300. break;
  46301. case PMREMGenerator.CP_EDGE_RIGHT:
  46302. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  46303. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  46304. break;
  46305. case PMREMGenerator.CP_EDGE_TOP:
  46306. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  46307. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  46308. break;
  46309. case PMREMGenerator.CP_EDGE_BOTTOM:
  46310. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  46311. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  46312. break;
  46313. }
  46314. //clamp filter extents in non-center tap faces to remain within surface
  46315. filterExtents[neighborFace].clampMin(0, 0, 0);
  46316. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  46317. }
  46318. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  46319. // from the center tap face, then process the opposite face entirely for now.
  46320. //Note that the cases in which this happens, what usually happens is that
  46321. // more than one edge bleeds onto the opposite face, and the bounding box
  46322. // encompasses the entire cube map face.
  46323. if (bleedOverAmount[i] > srcSize) {
  46324. //determine opposite face
  46325. switch (faceIdx) {
  46326. case PMREMGenerator.CP_FACE_X_POS:
  46327. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  46328. break;
  46329. case PMREMGenerator.CP_FACE_X_NEG:
  46330. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  46331. break;
  46332. case PMREMGenerator.CP_FACE_Y_POS:
  46333. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  46334. break;
  46335. case PMREMGenerator.CP_FACE_Y_NEG:
  46336. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  46337. break;
  46338. case PMREMGenerator.CP_FACE_Z_POS:
  46339. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  46340. break;
  46341. case PMREMGenerator.CP_FACE_Z_NEG:
  46342. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  46343. break;
  46344. default:
  46345. break;
  46346. }
  46347. //just encompass entire face for now
  46348. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  46349. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  46350. }
  46351. }
  46352. };
  46353. //--------------------------------------------------------------------------------------
  46354. //ProcessFilterExtents
  46355. // Process bounding box in each cube face
  46356. //
  46357. //--------------------------------------------------------------------------------------
  46358. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  46359. //accumulators are 64-bit floats in order to have the precision needed
  46360. // over a summation of a large number of pixels
  46361. var dstAccum = [0, 0, 0, 0];
  46362. var weightAccum = 0;
  46363. var k = 0;
  46364. var nSrcChannels = this.numChannels;
  46365. // norm cube map and srcCubeMap have same face width
  46366. var faceWidth = srcSize;
  46367. //amount to add to pointer to move to next scanline in images
  46368. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  46369. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  46370. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  46371. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  46372. // iterate over cubefaces
  46373. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  46374. //if bbox is non empty
  46375. if (!filterExtents[iFaceIdx].empty()) {
  46376. var uStart = filterExtents[iFaceIdx].min.x;
  46377. var vStart = filterExtents[iFaceIdx].min.y;
  46378. var uEnd = filterExtents[iFaceIdx].max.x;
  46379. var vEnd = filterExtents[iFaceIdx].max.y;
  46380. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  46381. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  46382. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  46383. for (var v = vStart; v <= vEnd; v++) {
  46384. var normCubeRowWalk = 0;
  46385. var srcCubeRowWalk = 0;
  46386. for (var u = uStart; u <= uEnd; u++) {
  46387. //pointer to direction in cube map associated with texel
  46388. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  46389. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  46390. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  46391. //check dot product to see if texel is within cone
  46392. var tapDotProd = texelVectX * centerTapDir.x +
  46393. texelVectY * centerTapDir.y +
  46394. texelVectZ * centerTapDir.z;
  46395. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  46396. //solid angle stored in 4th channel of normalizer/solid angle cube map
  46397. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  46398. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  46399. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  46400. // so just adding one to specularpower do the trick.
  46401. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  46402. //iterate over channels
  46403. for (k = 0; k < nSrcChannels; k++) {
  46404. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  46405. srcCubeRowWalk++;
  46406. }
  46407. weightAccum += weight; //accumulate weight
  46408. }
  46409. else {
  46410. //step across source pixel
  46411. srcCubeRowWalk += nSrcChannels;
  46412. }
  46413. normCubeRowWalk += 4; // 4 channels per norm cube map.
  46414. }
  46415. startIndexNormCubeMap += normCubePitch;
  46416. startIndexSrcCubeMap += srcCubePitch;
  46417. }
  46418. }
  46419. }
  46420. //divide through by weights if weight is non zero
  46421. if (weightAccum != 0.0) {
  46422. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  46423. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  46424. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  46425. if (this.numChannels > 3) {
  46426. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  46427. }
  46428. }
  46429. else {
  46430. // otherwise sample nearest
  46431. // get face idx and u, v texel coordinate in face
  46432. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  46433. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  46434. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  46435. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  46436. if (this.numChannels > 3) {
  46437. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  46438. }
  46439. }
  46440. return PMREMGenerator._vectorTemp;
  46441. };
  46442. //--------------------------------------------------------------------------------------
  46443. // Fixup cube edges
  46444. //
  46445. // average texels on cube map faces across the edges
  46446. // WARP/BENT Method Only.
  46447. //--------------------------------------------------------------------------------------
  46448. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  46449. var k;
  46450. var j;
  46451. var i;
  46452. var iFace;
  46453. var iCorner = 0;
  46454. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  46455. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  46456. // note that if functionality to filter across the three texels for each corner, then
  46457. //indexed by corner and face idx. the array contains the face the start points belongs to.
  46458. var cornerPtr = [
  46459. [[], [], []],
  46460. [[], [], []],
  46461. [[], [], []],
  46462. [[], [], []],
  46463. [[], [], []],
  46464. [[], [], []],
  46465. [[], [], []],
  46466. [[], [], []]
  46467. ];
  46468. //if there is no fixup, or fixup width = 0, do nothing
  46469. if (cubeMapSize < 1) {
  46470. return;
  46471. }
  46472. //special case 1x1 cubemap, average face colors
  46473. if (cubeMapSize == 1) {
  46474. //iterate over channels
  46475. for (k = 0; k < this.numChannels; k++) {
  46476. var accum = 0.0;
  46477. //iterate over faces to accumulate face colors
  46478. for (iFace = 0; iFace < 6; iFace++) {
  46479. accum += cubeMap[iFace][k];
  46480. }
  46481. //compute average over 6 face colors
  46482. accum /= 6.0;
  46483. //iterate over faces to distribute face colors
  46484. for (iFace = 0; iFace < 6; iFace++) {
  46485. cubeMap[iFace][k] = accum;
  46486. }
  46487. }
  46488. return;
  46489. }
  46490. //iterate over faces to collect list of corner texel pointers
  46491. for (iFace = 0; iFace < 6; iFace++) {
  46492. //the 4 corner pointers for this face
  46493. faceCornerStartIndicies[0] = [iFace, 0];
  46494. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  46495. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  46496. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  46497. //iterate over face corners to collect cube corner pointers
  46498. for (iCorner = 0; iCorner < 4; iCorner++) {
  46499. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  46500. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  46501. cornerNumPtrs[corner]++;
  46502. }
  46503. }
  46504. //iterate over corners to average across corner tap values
  46505. for (iCorner = 0; iCorner < 8; iCorner++) {
  46506. for (k = 0; k < this.numChannels; k++) {
  46507. var cornerTapAccum = 0.0;
  46508. //iterate over corner texels and average results
  46509. for (i = 0; i < 3; i++) {
  46510. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  46511. }
  46512. //divide by 3 to compute average of corner tap values
  46513. cornerTapAccum *= (1.0 / 3.0);
  46514. //iterate over corner texels and average results
  46515. for (i = 0; i < 3; i++) {
  46516. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  46517. }
  46518. }
  46519. }
  46520. //iterate over the twelve edges of the cube to average across edges
  46521. for (i = 0; i < 12; i++) {
  46522. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  46523. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  46524. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  46525. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  46526. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  46527. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  46528. var edgeWalk = 0;
  46529. var neighborEdgeWalk = 0;
  46530. //Determine walking pointers based on edge type
  46531. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  46532. switch (edge) {
  46533. case PMREMGenerator.CP_EDGE_LEFT:
  46534. // no change to faceEdgeStartPtr
  46535. edgeWalk = this.numChannels * cubeMapSize;
  46536. break;
  46537. case PMREMGenerator.CP_EDGE_RIGHT:
  46538. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46539. edgeWalk = this.numChannels * cubeMapSize;
  46540. break;
  46541. case PMREMGenerator.CP_EDGE_TOP:
  46542. // no change to faceEdgeStartPtr
  46543. edgeWalk = this.numChannels;
  46544. break;
  46545. case PMREMGenerator.CP_EDGE_BOTTOM:
  46546. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  46547. edgeWalk = this.numChannels;
  46548. break;
  46549. }
  46550. //For certain types of edge abutments, the neighbor edge walk needs to
  46551. // be flipped: the cases are
  46552. // if a left edge mates with a left or bottom edge on the neighbor
  46553. // if a top edge mates with a top or right edge on the neighbor
  46554. // if a right edge mates with a right or top edge on the neighbor
  46555. // if a bottom edge mates with a bottom or left edge on the neighbor
  46556. //Seeing as the edges are enumerated as follows
  46557. // left =0
  46558. // right =1
  46559. // top =2
  46560. // bottom =3
  46561. //
  46562. //If the edge enums are the same, or the sum of the enums == 3,
  46563. // the neighbor edge walk needs to be flipped
  46564. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  46565. switch (neighborEdge) {
  46566. case PMREMGenerator.CP_EDGE_LEFT:
  46567. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  46568. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  46569. break;
  46570. case PMREMGenerator.CP_EDGE_RIGHT:
  46571. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  46572. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  46573. break;
  46574. case PMREMGenerator.CP_EDGE_TOP:
  46575. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46576. neighborEdgeWalk = -this.numChannels;
  46577. break;
  46578. case PMREMGenerator.CP_EDGE_BOTTOM:
  46579. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  46580. neighborEdgeWalk = -this.numChannels;
  46581. break;
  46582. }
  46583. }
  46584. else {
  46585. //swapped direction neighbor edge walk
  46586. switch (neighborEdge) {
  46587. case PMREMGenerator.CP_EDGE_LEFT:
  46588. //no change to neighborEdgeStartPtr for this case since it points
  46589. // to the upper left corner already
  46590. neighborEdgeWalk = this.numChannels * cubeMapSize;
  46591. break;
  46592. case PMREMGenerator.CP_EDGE_RIGHT:
  46593. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46594. neighborEdgeWalk = this.numChannels * cubeMapSize;
  46595. break;
  46596. case PMREMGenerator.CP_EDGE_TOP:
  46597. //no change to neighborEdgeStartPtr for this case since it points
  46598. // to the upper left corner already
  46599. neighborEdgeWalk = this.numChannels;
  46600. break;
  46601. case PMREMGenerator.CP_EDGE_BOTTOM:
  46602. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  46603. neighborEdgeWalk = this.numChannels;
  46604. break;
  46605. }
  46606. }
  46607. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  46608. //nearby neighborhood
  46609. //step ahead one texel on edge
  46610. edgeStartIndex += edgeWalk;
  46611. neighborEdgeStartIndex += neighborEdgeWalk;
  46612. // note that this loop does not process the corner texels, since they have already been
  46613. // averaged across faces across earlier
  46614. for (j = 1; j < (cubeMapSize - 1); j++) {
  46615. //for each set of taps along edge, average them
  46616. // and rewrite the results into the edges
  46617. for (k = 0; k < this.numChannels; k++) {
  46618. var edgeTap = cubeMap[face][edgeStartIndex + k];
  46619. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  46620. //compute average of tap intensity values
  46621. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  46622. //propagate average of taps to edge taps
  46623. cubeMap[face][edgeStartIndex + k] = avgTap;
  46624. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  46625. }
  46626. edgeStartIndex += edgeWalk;
  46627. neighborEdgeStartIndex += neighborEdgeWalk;
  46628. }
  46629. }
  46630. };
  46631. return PMREMGenerator;
  46632. }());
  46633. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  46634. PMREMGenerator.CP_UDIR = 0;
  46635. PMREMGenerator.CP_VDIR = 1;
  46636. PMREMGenerator.CP_FACEAXIS = 2;
  46637. //used to index cube faces
  46638. PMREMGenerator.CP_FACE_X_POS = 0;
  46639. PMREMGenerator.CP_FACE_X_NEG = 1;
  46640. PMREMGenerator.CP_FACE_Y_POS = 2;
  46641. PMREMGenerator.CP_FACE_Y_NEG = 3;
  46642. PMREMGenerator.CP_FACE_Z_POS = 4;
  46643. PMREMGenerator.CP_FACE_Z_NEG = 5;
  46644. //used to index image edges
  46645. // NOTE.. the actual number corresponding to the edge is important
  46646. // do not change these, or the code will break
  46647. //
  46648. // CP_EDGE_LEFT is u = 0
  46649. // CP_EDGE_RIGHT is u = width-1
  46650. // CP_EDGE_TOP is v = 0
  46651. // CP_EDGE_BOTTOM is v = height-1
  46652. PMREMGenerator.CP_EDGE_LEFT = 0;
  46653. PMREMGenerator.CP_EDGE_RIGHT = 1;
  46654. PMREMGenerator.CP_EDGE_TOP = 2;
  46655. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  46656. //corners of CUBE map (P or N specifys if it corresponds to the
  46657. // positive or negative direction each of X, Y, and Z
  46658. PMREMGenerator.CP_CORNER_NNN = 0;
  46659. PMREMGenerator.CP_CORNER_NNP = 1;
  46660. PMREMGenerator.CP_CORNER_NPN = 2;
  46661. PMREMGenerator.CP_CORNER_NPP = 3;
  46662. PMREMGenerator.CP_CORNER_PNN = 4;
  46663. PMREMGenerator.CP_CORNER_PNP = 5;
  46664. PMREMGenerator.CP_CORNER_PPN = 6;
  46665. PMREMGenerator.CP_CORNER_PPP = 7;
  46666. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  46667. //3x2 matrices that map cube map indexing vectors in 3d
  46668. // (after face selection and divide through by the
  46669. // _ABSOLUTE VALUE_ of the max coord)
  46670. // into NVC space
  46671. //Note this currently assumes the D3D cube face ordering and orientation
  46672. PMREMGenerator._sgFace2DMapping = [
  46673. //XPOS face
  46674. [[0, 0, -1],
  46675. [0, -1, 0],
  46676. [1, 0, 0]],
  46677. //XNEG face
  46678. [[0, 0, 1],
  46679. [0, -1, 0],
  46680. [-1, 0, 0]],
  46681. //YPOS face
  46682. [[1, 0, 0],
  46683. [0, 0, 1],
  46684. [0, 1, 0]],
  46685. //YNEG face
  46686. [[1, 0, 0],
  46687. [0, 0, -1],
  46688. [0, -1, 0]],
  46689. //ZPOS face
  46690. [[1, 0, 0],
  46691. [0, -1, 0],
  46692. [0, 0, 1]],
  46693. //ZNEG face
  46694. [[-1, 0, 0],
  46695. [0, -1, 0],
  46696. [0, 0, -1]],
  46697. ];
  46698. //------------------------------------------------------------------------------
  46699. // D3D cube map face specification
  46700. // mapping from 3D x,y,z cube map lookup coordinates
  46701. // to 2D within face u,v coordinates
  46702. //
  46703. // --------------------> U direction
  46704. // | (within-face texture space)
  46705. // | _____
  46706. // | | |
  46707. // | | +Y |
  46708. // | _____|_____|_____ _____
  46709. // | | | | | |
  46710. // | | -X | +Z | +X | -Z |
  46711. // | |_____|_____|_____|_____|
  46712. // | | |
  46713. // | | -Y |
  46714. // | |_____|
  46715. // |
  46716. // v V direction
  46717. // (within-face texture space)
  46718. //------------------------------------------------------------------------------
  46719. //Information about neighbors and how texture coorrdinates change across faces
  46720. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  46721. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  46722. //Note this currently assumes the D3D cube face ordering and orientation
  46723. PMREMGenerator._sgCubeNgh = [
  46724. //XPOS face
  46725. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46726. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46727. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46728. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  46729. //XNEG face
  46730. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46731. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  46732. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  46733. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  46734. //YPOS face
  46735. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  46736. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  46737. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  46738. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  46739. //YNEG face
  46740. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  46741. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46742. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46743. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  46744. //ZPOS face
  46745. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46746. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  46747. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46748. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  46749. //ZNEG face
  46750. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46751. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46752. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  46753. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  46754. ];
  46755. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  46756. // this table is used to average over the edges.
  46757. PMREMGenerator._sgCubeEdgeList = [
  46758. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  46759. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46760. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  46761. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46762. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46763. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46764. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  46765. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  46766. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  46767. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46768. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  46769. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  46770. ];
  46771. //Information about which of the 8 cube corners are correspond to the
  46772. // the 4 corners in each cube face
  46773. // the order is upper left, upper right, lower left, lower right
  46774. PMREMGenerator._sgCubeCornerList = [
  46775. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  46776. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  46777. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  46778. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  46779. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  46780. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  46781. ];
  46782. Internals.PMREMGenerator = PMREMGenerator;
  46783. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46784. })(BABYLON || (BABYLON = {}));
  46785. //# sourceMappingURL=babylon.pmremgenerator.js.map
  46786. var BABYLON;
  46787. (function (BABYLON) {
  46788. /**
  46789. * This represents a texture coming from an HDR input.
  46790. *
  46791. * The only supported format is currently panorama picture stored in RGBE format.
  46792. * Example of such files can be found on HDRLib: http://hdrlib.com/
  46793. */
  46794. var HDRCubeTexture = (function (_super) {
  46795. __extends(HDRCubeTexture, _super);
  46796. /**
  46797. * Instantiates an HDRTexture from the following parameters.
  46798. *
  46799. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  46800. * @param scene The scene the texture will be used in
  46801. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  46802. * @param noMipmap Forces to not generate the mipmap if true
  46803. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  46804. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  46805. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  46806. */
  46807. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  46808. if (noMipmap === void 0) { noMipmap = false; }
  46809. if (generateHarmonics === void 0) { generateHarmonics = true; }
  46810. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  46811. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  46812. if (onLoad === void 0) { onLoad = null; }
  46813. if (onError === void 0) { onError = null; }
  46814. var _this = _super.call(this, scene) || this;
  46815. _this._useInGammaSpace = false;
  46816. _this._generateHarmonics = true;
  46817. _this._isBABYLONPreprocessed = false;
  46818. _this._onLoad = null;
  46819. _this._onError = null;
  46820. /**
  46821. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  46822. */
  46823. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  46824. /**
  46825. * The spherical polynomial data extracted from the texture.
  46826. */
  46827. _this.sphericalPolynomial = null;
  46828. /**
  46829. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  46830. * This is usefull at run time to apply the good shader.
  46831. */
  46832. _this.isPMREM = false;
  46833. _this._isBlocking = true;
  46834. if (!url) {
  46835. return _this;
  46836. }
  46837. _this.name = url;
  46838. _this.url = url;
  46839. _this.hasAlpha = false;
  46840. _this.isCube = true;
  46841. _this._textureMatrix = BABYLON.Matrix.Identity();
  46842. _this._onLoad = onLoad;
  46843. _this._onError = onError;
  46844. if (size) {
  46845. _this._isBABYLONPreprocessed = false;
  46846. _this._noMipmap = noMipmap;
  46847. _this._size = size;
  46848. _this._useInGammaSpace = useInGammaSpace;
  46849. _this._usePMREMGenerator = usePMREMGenerator &&
  46850. scene.getEngine().getCaps().textureLOD &&
  46851. _this.getScene().getEngine().getCaps().textureFloat &&
  46852. !_this._useInGammaSpace;
  46853. }
  46854. else {
  46855. _this._isBABYLONPreprocessed = true;
  46856. _this._noMipmap = false;
  46857. _this._useInGammaSpace = false;
  46858. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  46859. _this.getScene().getEngine().getCaps().textureFloat &&
  46860. !_this._useInGammaSpace;
  46861. }
  46862. _this.isPMREM = _this._usePMREMGenerator;
  46863. _this._texture = _this._getFromCache(url, _this._noMipmap);
  46864. if (!_this._texture) {
  46865. if (!scene.useDelayedTextureLoading) {
  46866. _this.loadTexture();
  46867. }
  46868. else {
  46869. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  46870. }
  46871. }
  46872. return _this;
  46873. }
  46874. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  46875. /**
  46876. * Gets wether or not the texture is blocking during loading.
  46877. */
  46878. get: function () {
  46879. return this._isBlocking;
  46880. },
  46881. /**
  46882. * Sets wether or not the texture is blocking during loading.
  46883. */
  46884. set: function (value) {
  46885. this._isBlocking = value;
  46886. },
  46887. enumerable: true,
  46888. configurable: true
  46889. });
  46890. /**
  46891. * Occurs when the file is a preprocessed .babylon.hdr file.
  46892. */
  46893. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  46894. var _this = this;
  46895. var mipLevels = 0;
  46896. var floatArrayView = null;
  46897. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  46898. var mips = [];
  46899. var startIndex = 30;
  46900. for (var level = 0; level < mipLevels; level++) {
  46901. mips.push([]);
  46902. // Fill each pixel of the mip level.
  46903. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  46904. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46905. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  46906. mips[level].push(faceData);
  46907. startIndex += faceSize;
  46908. }
  46909. }
  46910. return mips;
  46911. } : null;
  46912. var callback = function (buffer) {
  46913. // Create Native Array Views
  46914. var intArrayView = new Int32Array(buffer);
  46915. floatArrayView = new Float32Array(buffer);
  46916. // Fill header.
  46917. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  46918. _this._size = intArrayView[1]; // CubeMap max mip face size.
  46919. // Update Texture Information.
  46920. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  46921. // Fill polynomial information.
  46922. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  46923. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  46924. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  46925. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  46926. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  46927. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  46928. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  46929. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  46930. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  46931. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  46932. // Fill pixel data.
  46933. mipLevels = intArrayView[29]; // Number of mip levels.
  46934. var startIndex = 30;
  46935. var data = [];
  46936. var faceSize = Math.pow(_this._size, 2) * 3;
  46937. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46938. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  46939. startIndex += faceSize;
  46940. }
  46941. var results = [];
  46942. var byteArray = null;
  46943. // Push each faces.
  46944. for (var k = 0; k < 6; k++) {
  46945. var dataFace = null;
  46946. // If special cases.
  46947. if (!mipmapGenerator) {
  46948. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  46949. dataFace = data[j];
  46950. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  46951. // 3 channels of 1 bytes per pixel in bytes.
  46952. var byteBuffer = new ArrayBuffer(faceSize);
  46953. byteArray = new Uint8Array(byteBuffer);
  46954. }
  46955. for (var i = 0; i < _this._size * _this._size; i++) {
  46956. // Put in gamma space if requested.
  46957. if (_this._useInGammaSpace) {
  46958. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  46959. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  46960. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  46961. }
  46962. // Convert to int texture for fallback.
  46963. if (byteArray) {
  46964. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  46965. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  46966. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  46967. // May use luminance instead if the result is not accurate.
  46968. var max = Math.max(Math.max(r, g), b);
  46969. if (max > 255) {
  46970. var scale = 255 / max;
  46971. r *= scale;
  46972. g *= scale;
  46973. b *= scale;
  46974. }
  46975. byteArray[(i * 3) + 0] = r;
  46976. byteArray[(i * 3) + 1] = g;
  46977. byteArray[(i * 3) + 2] = b;
  46978. }
  46979. }
  46980. }
  46981. else {
  46982. dataFace = data[k];
  46983. }
  46984. // Fill the array accordingly.
  46985. if (byteArray) {
  46986. results.push(byteArray);
  46987. }
  46988. else {
  46989. results.push(dataFace);
  46990. }
  46991. }
  46992. return results;
  46993. };
  46994. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  46995. };
  46996. /**
  46997. * Occurs when the file is raw .hdr file.
  46998. */
  46999. HDRCubeTexture.prototype.loadHDRTexture = function () {
  47000. var _this = this;
  47001. var callback = function (buffer) {
  47002. // Extract the raw linear data.
  47003. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  47004. // Generate harmonics if needed.
  47005. if (_this._generateHarmonics) {
  47006. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  47007. }
  47008. var results = [];
  47009. var byteArray = null;
  47010. // Push each faces.
  47011. for (var j = 0; j < 6; j++) {
  47012. // Create uintarray fallback.
  47013. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  47014. // 3 channels of 1 bytes per pixel in bytes.
  47015. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  47016. byteArray = new Uint8Array(byteBuffer);
  47017. }
  47018. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  47019. // If special cases.
  47020. if (_this._useInGammaSpace || byteArray) {
  47021. for (var i = 0; i < _this._size * _this._size; i++) {
  47022. // Put in gamma space if requested.
  47023. if (_this._useInGammaSpace) {
  47024. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  47025. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  47026. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  47027. }
  47028. // Convert to int texture for fallback.
  47029. if (byteArray) {
  47030. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  47031. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  47032. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  47033. // May use luminance instead if the result is not accurate.
  47034. var max = Math.max(Math.max(r, g), b);
  47035. if (max > 255) {
  47036. var scale = 255 / max;
  47037. r *= scale;
  47038. g *= scale;
  47039. b *= scale;
  47040. }
  47041. byteArray[(i * 3) + 0] = r;
  47042. byteArray[(i * 3) + 1] = g;
  47043. byteArray[(i * 3) + 2] = b;
  47044. }
  47045. }
  47046. }
  47047. if (byteArray) {
  47048. results.push(byteArray);
  47049. }
  47050. else {
  47051. results.push(dataFace);
  47052. }
  47053. }
  47054. return results;
  47055. };
  47056. var mipmapGenerator = null;
  47057. if (!this._noMipmap &&
  47058. this._usePMREMGenerator) {
  47059. mipmapGenerator = function (data) {
  47060. // Custom setup of the generator matching with the PBR shader values.
  47061. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  47062. return generator.filterCubeMap();
  47063. };
  47064. }
  47065. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  47066. };
  47067. /**
  47068. * Starts the loading process of the texture.
  47069. */
  47070. HDRCubeTexture.prototype.loadTexture = function () {
  47071. if (this._isBABYLONPreprocessed) {
  47072. this.loadBabylonTexture();
  47073. }
  47074. else {
  47075. this.loadHDRTexture();
  47076. }
  47077. };
  47078. HDRCubeTexture.prototype.clone = function () {
  47079. var size = this._isBABYLONPreprocessed ? null : this._size;
  47080. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  47081. // Base texture
  47082. newTexture.level = this.level;
  47083. newTexture.wrapU = this.wrapU;
  47084. newTexture.wrapV = this.wrapV;
  47085. newTexture.coordinatesIndex = this.coordinatesIndex;
  47086. newTexture.coordinatesMode = this.coordinatesMode;
  47087. return newTexture;
  47088. };
  47089. // Methods
  47090. HDRCubeTexture.prototype.delayLoad = function () {
  47091. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  47092. return;
  47093. }
  47094. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  47095. this._texture = this._getFromCache(this.url, this._noMipmap);
  47096. if (!this._texture) {
  47097. this.loadTexture();
  47098. }
  47099. };
  47100. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  47101. return this._textureMatrix;
  47102. };
  47103. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  47104. var texture = null;
  47105. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  47106. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  47107. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  47108. texture.name = parsedTexture.name;
  47109. texture.hasAlpha = parsedTexture.hasAlpha;
  47110. texture.level = parsedTexture.level;
  47111. texture.coordinatesMode = parsedTexture.coordinatesMode;
  47112. texture.isBlocking = parsedTexture.isBlocking;
  47113. }
  47114. return texture;
  47115. };
  47116. HDRCubeTexture.prototype.serialize = function () {
  47117. if (!this.name) {
  47118. return null;
  47119. }
  47120. var serializationObject = {};
  47121. serializationObject.name = this.name;
  47122. serializationObject.hasAlpha = this.hasAlpha;
  47123. serializationObject.isCube = true;
  47124. serializationObject.level = this.level;
  47125. serializationObject.size = this._size;
  47126. serializationObject.coordinatesMode = this.coordinatesMode;
  47127. serializationObject.useInGammaSpace = this._useInGammaSpace;
  47128. serializationObject.generateHarmonics = this._generateHarmonics;
  47129. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  47130. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  47131. serializationObject.customType = "BABYLON.HDRCubeTexture";
  47132. serializationObject.noMipmap = this._noMipmap;
  47133. serializationObject.isBlocking = this._isBlocking;
  47134. return serializationObject;
  47135. };
  47136. /**
  47137. * Saves as a file the data contained in the texture in a binary format.
  47138. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  47139. * as the spherical used in the lighting.
  47140. * @param url The HDR file url.
  47141. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  47142. * @param onError Method called if any error happens during download.
  47143. * @return The packed binary data.
  47144. */
  47145. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  47146. if (onError === void 0) { onError = null; }
  47147. var callback = function (buffer) {
  47148. var data = new Blob([buffer], { type: 'application/octet-stream' });
  47149. // Returns a URL you can use as a href.
  47150. var objUrl = window.URL.createObjectURL(data);
  47151. // Simulates a link to it and click to dowload.
  47152. var a = document.createElement("a");
  47153. document.body.appendChild(a);
  47154. a.style.display = "none";
  47155. a.href = objUrl;
  47156. a.download = "envmap.babylon.hdr";
  47157. a.click();
  47158. };
  47159. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  47160. };
  47161. /**
  47162. * Serializes the data contained in the texture in a binary format.
  47163. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  47164. * as the spherical used in the lighting.
  47165. * @param url The HDR file url.
  47166. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  47167. * @param onError Method called if any error happens during download.
  47168. * @return The packed binary data.
  47169. */
  47170. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  47171. if (onError === void 0) { onError = null; }
  47172. // Needs the url tho create the texture.
  47173. if (!url) {
  47174. return null;
  47175. }
  47176. // Check Power of two size.
  47177. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  47178. return null;
  47179. }
  47180. var getDataCallback = function (dataBuffer) {
  47181. // Extract the raw linear data.
  47182. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  47183. // Generate harmonics if needed.
  47184. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  47185. // Generate seamless faces
  47186. var mipGeneratorArray = [];
  47187. // Data are known to be in +X +Y +Z -X -Y -Z
  47188. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  47189. mipGeneratorArray.push(cubeData.right); // +X
  47190. mipGeneratorArray.push(cubeData.left); // -X
  47191. mipGeneratorArray.push(cubeData.up); // +Y
  47192. mipGeneratorArray.push(cubeData.down); // -Y
  47193. mipGeneratorArray.push(cubeData.front); // +Z
  47194. mipGeneratorArray.push(cubeData.back); // -Z
  47195. // Custom setup of the generator matching with the PBR shader values.
  47196. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  47197. var mippedData = generator.filterCubeMap();
  47198. // Compute required byte length.
  47199. var byteLength = 1 * 4; // Raw Data Version int32.
  47200. byteLength += 4; // CubeMap max mip face size int32.
  47201. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  47202. // Add data size.
  47203. byteLength += 4; // Number of mip levels int32.
  47204. for (var level = 0; level < mippedData.length; level++) {
  47205. var mipSize = size >> level;
  47206. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  47207. }
  47208. // Prepare binary structure.
  47209. var buffer = new ArrayBuffer(byteLength);
  47210. var intArrayView = new Int32Array(buffer);
  47211. var floatArrayView = new Float32Array(buffer);
  47212. // Fill header.
  47213. intArrayView[0] = 1; // Version 1.
  47214. intArrayView[1] = size; // CubeMap max mip face size.
  47215. // Fill polynomial information.
  47216. sphericalPolynomial.x.toArray(floatArrayView, 2);
  47217. sphericalPolynomial.y.toArray(floatArrayView, 5);
  47218. sphericalPolynomial.z.toArray(floatArrayView, 8);
  47219. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  47220. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  47221. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  47222. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  47223. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  47224. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  47225. // Fill pixel data.
  47226. intArrayView[29] = mippedData.length; // Number of mip levels.
  47227. var startIndex = 30;
  47228. for (var level = 0; level < mippedData.length; level++) {
  47229. // Fill each pixel of the mip level.
  47230. var faceSize = Math.pow(size >> level, 2) * 3;
  47231. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47232. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  47233. startIndex += faceSize;
  47234. }
  47235. }
  47236. // Callback.
  47237. callback(buffer);
  47238. };
  47239. // Download and process.
  47240. BABYLON.Tools.LoadFile(url, function (data) {
  47241. getDataCallback(data);
  47242. }, null, null, true, onError);
  47243. };
  47244. return HDRCubeTexture;
  47245. }(BABYLON.BaseTexture));
  47246. HDRCubeTexture._facesMapping = [
  47247. "right",
  47248. "up",
  47249. "front",
  47250. "left",
  47251. "down",
  47252. "back"
  47253. ];
  47254. BABYLON.HDRCubeTexture = HDRCubeTexture;
  47255. })(BABYLON || (BABYLON = {}));
  47256. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  47257. var BABYLON;
  47258. (function (BABYLON) {
  47259. var DefaultLoadingScreen = (function () {
  47260. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  47261. if (_loadingText === void 0) { _loadingText = ""; }
  47262. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  47263. var _this = this;
  47264. this._renderingCanvas = _renderingCanvas;
  47265. this._loadingText = _loadingText;
  47266. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  47267. // Resize
  47268. this._resizeLoadingUI = function () {
  47269. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  47270. _this._loadingDiv.style.position = "absolute";
  47271. _this._loadingDiv.style.left = canvasRect.left + "px";
  47272. _this._loadingDiv.style.top = canvasRect.top + "px";
  47273. _this._loadingDiv.style.width = canvasRect.width + "px";
  47274. _this._loadingDiv.style.height = canvasRect.height + "px";
  47275. };
  47276. }
  47277. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47278. if (this._loadingDiv) {
  47279. // Do not add a loading screen if there is already one
  47280. return;
  47281. }
  47282. this._loadingDiv = document.createElement("div");
  47283. this._loadingDiv.id = "babylonjsLoadingDiv";
  47284. this._loadingDiv.style.opacity = "0";
  47285. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47286. // Loading text
  47287. this._loadingTextDiv = document.createElement("div");
  47288. this._loadingTextDiv.style.position = "absolute";
  47289. this._loadingTextDiv.style.left = "0";
  47290. this._loadingTextDiv.style.top = "50%";
  47291. this._loadingTextDiv.style.marginTop = "80px";
  47292. this._loadingTextDiv.style.width = "100%";
  47293. this._loadingTextDiv.style.height = "20px";
  47294. this._loadingTextDiv.style.fontFamily = "Arial";
  47295. this._loadingTextDiv.style.fontSize = "14px";
  47296. this._loadingTextDiv.style.color = "white";
  47297. this._loadingTextDiv.style.textAlign = "center";
  47298. this._loadingTextDiv.innerHTML = "Loading";
  47299. this._loadingDiv.appendChild(this._loadingTextDiv);
  47300. //set the predefined text
  47301. this._loadingTextDiv.innerHTML = this._loadingText;
  47302. // Generating keyframes
  47303. var style = document.createElement('style');
  47304. style.type = 'text/css';
  47305. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  47306. style.innerHTML = keyFrames;
  47307. document.getElementsByTagName('head')[0].appendChild(style);
  47308. // Loading img
  47309. var imgBack = new Image();
  47310. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  47311. imgBack.style.position = "absolute";
  47312. imgBack.style.left = "50%";
  47313. imgBack.style.top = "50%";
  47314. imgBack.style.marginLeft = "-50px";
  47315. imgBack.style.marginTop = "-50px";
  47316. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47317. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47318. imgBack.style.transformOrigin = "50% 50%";
  47319. imgBack.style.webkitTransformOrigin = "50% 50%";
  47320. this._loadingDiv.appendChild(imgBack);
  47321. this._resizeLoadingUI();
  47322. window.addEventListener("resize", this._resizeLoadingUI);
  47323. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47324. document.body.appendChild(this._loadingDiv);
  47325. this._loadingDiv.style.opacity = "1";
  47326. };
  47327. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47328. var _this = this;
  47329. if (!this._loadingDiv) {
  47330. return;
  47331. }
  47332. var onTransitionEnd = function () {
  47333. if (!_this._loadingDiv) {
  47334. return;
  47335. }
  47336. document.body.removeChild(_this._loadingDiv);
  47337. window.removeEventListener("resize", _this._resizeLoadingUI);
  47338. _this._loadingDiv = null;
  47339. };
  47340. this._loadingDiv.style.opacity = "0";
  47341. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47342. };
  47343. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47344. set: function (text) {
  47345. this._loadingText = text;
  47346. if (this._loadingTextDiv) {
  47347. this._loadingTextDiv.innerHTML = this._loadingText;
  47348. }
  47349. },
  47350. enumerable: true,
  47351. configurable: true
  47352. });
  47353. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47354. get: function () {
  47355. return this._loadingDivBackgroundColor;
  47356. },
  47357. set: function (color) {
  47358. this._loadingDivBackgroundColor = color;
  47359. if (!this._loadingDiv) {
  47360. return;
  47361. }
  47362. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47363. },
  47364. enumerable: true,
  47365. configurable: true
  47366. });
  47367. return DefaultLoadingScreen;
  47368. }());
  47369. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47370. })(BABYLON || (BABYLON = {}));
  47371. //# sourceMappingURL=babylon.loadingScreen.js.map
  47372. var BABYLON;
  47373. (function (BABYLON) {
  47374. var SceneLoader = (function () {
  47375. function SceneLoader() {
  47376. }
  47377. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47378. get: function () {
  47379. return 0;
  47380. },
  47381. enumerable: true,
  47382. configurable: true
  47383. });
  47384. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47385. get: function () {
  47386. return 1;
  47387. },
  47388. enumerable: true,
  47389. configurable: true
  47390. });
  47391. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47392. get: function () {
  47393. return 2;
  47394. },
  47395. enumerable: true,
  47396. configurable: true
  47397. });
  47398. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47399. get: function () {
  47400. return 3;
  47401. },
  47402. enumerable: true,
  47403. configurable: true
  47404. });
  47405. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47406. get: function () {
  47407. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47408. },
  47409. set: function (value) {
  47410. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47411. },
  47412. enumerable: true,
  47413. configurable: true
  47414. });
  47415. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47416. get: function () {
  47417. return SceneLoader._ShowLoadingScreen;
  47418. },
  47419. set: function (value) {
  47420. SceneLoader._ShowLoadingScreen = value;
  47421. },
  47422. enumerable: true,
  47423. configurable: true
  47424. });
  47425. Object.defineProperty(SceneLoader, "loggingLevel", {
  47426. get: function () {
  47427. return SceneLoader._loggingLevel;
  47428. },
  47429. set: function (value) {
  47430. SceneLoader._loggingLevel = value;
  47431. },
  47432. enumerable: true,
  47433. configurable: true
  47434. });
  47435. SceneLoader._getDefaultPlugin = function () {
  47436. return SceneLoader._registeredPlugins[".babylon"];
  47437. };
  47438. SceneLoader._getPluginForExtension = function (extension) {
  47439. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47440. if (registeredPlugin) {
  47441. return registeredPlugin;
  47442. }
  47443. return SceneLoader._getDefaultPlugin();
  47444. };
  47445. SceneLoader._getPluginForDirectLoad = function (data) {
  47446. for (var extension in SceneLoader._registeredPlugins) {
  47447. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47448. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47449. return SceneLoader._registeredPlugins[extension];
  47450. }
  47451. }
  47452. return SceneLoader._getDefaultPlugin();
  47453. };
  47454. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47455. if (sceneFilename.name) {
  47456. sceneFilename = sceneFilename.name;
  47457. }
  47458. var dotPosition = sceneFilename.lastIndexOf(".");
  47459. var queryStringPosition = sceneFilename.indexOf("?");
  47460. if (queryStringPosition === -1) {
  47461. queryStringPosition = sceneFilename.length;
  47462. }
  47463. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47464. return SceneLoader._getPluginForExtension(extension);
  47465. };
  47466. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47467. SceneLoader._getDirectLoad = function (sceneFilename) {
  47468. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47469. return sceneFilename.substr(5);
  47470. }
  47471. return null;
  47472. };
  47473. // Public functions
  47474. SceneLoader.GetPluginForExtension = function (extension) {
  47475. return SceneLoader._getPluginForExtension(extension).plugin;
  47476. };
  47477. SceneLoader.RegisterPlugin = function (plugin) {
  47478. if (typeof plugin.extensions === "string") {
  47479. var extension = plugin.extensions;
  47480. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47481. plugin: plugin,
  47482. isBinary: false
  47483. };
  47484. }
  47485. else {
  47486. var extensions = plugin.extensions;
  47487. Object.keys(extensions).forEach(function (extension) {
  47488. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47489. plugin: plugin,
  47490. isBinary: extensions[extension].isBinary
  47491. };
  47492. });
  47493. }
  47494. };
  47495. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47496. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47497. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47498. return;
  47499. }
  47500. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47501. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47502. return;
  47503. }
  47504. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47505. var loadingToken = {};
  47506. scene._addPendingData(loadingToken);
  47507. var manifestChecked = function (success) {
  47508. scene.database = database;
  47509. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  47510. var plugin = registeredPlugin.plugin;
  47511. var useArrayBuffer = registeredPlugin.isBinary;
  47512. var importMeshFromData = function (data) {
  47513. var meshes = [];
  47514. var particleSystems = [];
  47515. var skeletons = [];
  47516. if (scene.isDisposed) {
  47517. if (onerror) {
  47518. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  47519. }
  47520. return;
  47521. }
  47522. try {
  47523. if (plugin.importMesh) {
  47524. var syncedPlugin = plugin;
  47525. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  47526. if (onerror) {
  47527. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47528. }
  47529. scene._removePendingData(loadingToken);
  47530. return;
  47531. }
  47532. if (onsuccess) {
  47533. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47534. onsuccess(meshes, particleSystems, skeletons);
  47535. scene._removePendingData(loadingToken);
  47536. }
  47537. }
  47538. else {
  47539. var asyncedPlugin = plugin;
  47540. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47541. if (onsuccess) {
  47542. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47543. onsuccess(meshes, particleSystems, skeletons);
  47544. scene._removePendingData(loadingToken);
  47545. }
  47546. }, function () {
  47547. if (onerror) {
  47548. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47549. }
  47550. scene._removePendingData(loadingToken);
  47551. });
  47552. }
  47553. }
  47554. catch (e) {
  47555. if (onerror) {
  47556. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  47557. }
  47558. scene._removePendingData(loadingToken);
  47559. }
  47560. };
  47561. if (directLoad) {
  47562. importMeshFromData(directLoad);
  47563. return;
  47564. }
  47565. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  47566. importMeshFromData(data);
  47567. }, progressCallBack, database, useArrayBuffer, function () {
  47568. if (onerror) {
  47569. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  47570. }
  47571. });
  47572. };
  47573. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  47574. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47575. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47576. }
  47577. else {
  47578. // If the scene is a data stream or offline support is not enabled, it's a direct load
  47579. manifestChecked(true);
  47580. }
  47581. };
  47582. /**
  47583. * Load a scene
  47584. * @param rootUrl a string that defines the root url for scene and resources
  47585. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47586. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47587. */
  47588. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  47589. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  47590. };
  47591. /**
  47592. * Append a scene
  47593. * @param rootUrl a string that defines the root url for scene and resources
  47594. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47595. * @param scene is the instance of BABYLON.Scene to append to
  47596. */
  47597. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47598. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47599. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47600. return;
  47601. }
  47602. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47603. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47604. var plugin = registeredPlugin.plugin;
  47605. var useArrayBuffer = registeredPlugin.isBinary;
  47606. var database;
  47607. var loadingToken = {};
  47608. scene._addPendingData(loadingToken);
  47609. if (SceneLoader.ShowLoadingScreen) {
  47610. scene.getEngine().displayLoadingUI();
  47611. }
  47612. var loadSceneFromData = function (data) {
  47613. scene.database = database;
  47614. if (plugin.load) {
  47615. var syncedPlugin = plugin;
  47616. if (!syncedPlugin.load(scene, data, rootUrl)) {
  47617. if (onerror) {
  47618. onerror(scene);
  47619. }
  47620. scene._removePendingData(loadingToken);
  47621. scene.getEngine().hideLoadingUI();
  47622. return;
  47623. }
  47624. if (onsuccess) {
  47625. onsuccess(scene);
  47626. }
  47627. scene._removePendingData(loadingToken);
  47628. }
  47629. else {
  47630. var asyncedPlugin = plugin;
  47631. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47632. if (onsuccess) {
  47633. onsuccess(scene);
  47634. }
  47635. scene._removePendingData(loadingToken);
  47636. }, function () {
  47637. if (onerror) {
  47638. onerror(scene);
  47639. }
  47640. scene._removePendingData(loadingToken);
  47641. scene.getEngine().hideLoadingUI();
  47642. });
  47643. }
  47644. if (SceneLoader.ShowLoadingScreen) {
  47645. scene.executeWhenReady(function () {
  47646. scene.getEngine().hideLoadingUI();
  47647. });
  47648. }
  47649. };
  47650. var manifestChecked = function (success) {
  47651. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  47652. };
  47653. if (directLoad) {
  47654. loadSceneFromData(directLoad);
  47655. return;
  47656. }
  47657. if (rootUrl.indexOf("file:") === -1) {
  47658. if (scene.getEngine().enableOfflineSupport) {
  47659. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47660. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47661. }
  47662. else {
  47663. manifestChecked(true);
  47664. }
  47665. }
  47666. else {
  47667. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  47668. }
  47669. };
  47670. return SceneLoader;
  47671. }());
  47672. // Flags
  47673. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47674. SceneLoader._ShowLoadingScreen = true;
  47675. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47676. // Members
  47677. SceneLoader._registeredPlugins = {};
  47678. BABYLON.SceneLoader = SceneLoader;
  47679. ;
  47680. })(BABYLON || (BABYLON = {}));
  47681. //# sourceMappingURL=babylon.sceneLoader.js.map
  47682. var BABYLON;
  47683. (function (BABYLON) {
  47684. var Internals;
  47685. (function (Internals) {
  47686. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47687. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47688. var parsedMaterial = parsedData.materials[index];
  47689. if (parsedMaterial.id === id) {
  47690. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47691. }
  47692. }
  47693. return null;
  47694. };
  47695. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47696. names = (names instanceof Array) ? names : [names];
  47697. for (var i in names) {
  47698. if (mesh.name === names[i]) {
  47699. hierarchyIds.push(mesh.id);
  47700. return true;
  47701. }
  47702. }
  47703. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47704. hierarchyIds.push(mesh.id);
  47705. return true;
  47706. }
  47707. return false;
  47708. };
  47709. var logOperation = function (operation, producer) {
  47710. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47711. };
  47712. BABYLON.SceneLoader.RegisterPlugin({
  47713. extensions: ".babylon",
  47714. canDirectLoad: function (data) {
  47715. if (data.indexOf("babylon") !== -1) {
  47716. return true;
  47717. }
  47718. return false;
  47719. },
  47720. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47721. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47722. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47723. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47724. // and avoid problems with multiple concurrent .babylon loads.
  47725. var log = "importMesh has failed JSON parse";
  47726. try {
  47727. var parsedData = JSON.parse(data);
  47728. log = "";
  47729. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47730. var loadedSkeletonsIds = [];
  47731. var loadedMaterialsIds = [];
  47732. var hierarchyIds = [];
  47733. var index;
  47734. var cache;
  47735. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47736. var parsedMesh = parsedData.meshes[index];
  47737. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47738. if (meshesNames instanceof Array) {
  47739. // Remove found mesh name from list.
  47740. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47741. }
  47742. //Geometry?
  47743. if (parsedMesh.geometryId) {
  47744. //does the file contain geometries?
  47745. if (parsedData.geometries) {
  47746. //find the correct geometry and add it to the scene
  47747. var found = false;
  47748. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47749. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  47750. return;
  47751. }
  47752. else {
  47753. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47754. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47755. switch (geometryType) {
  47756. case "boxes":
  47757. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47758. break;
  47759. case "spheres":
  47760. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47761. break;
  47762. case "cylinders":
  47763. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47764. break;
  47765. case "toruses":
  47766. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47767. break;
  47768. case "grounds":
  47769. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47770. break;
  47771. case "planes":
  47772. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47773. break;
  47774. case "torusKnots":
  47775. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47776. break;
  47777. case "vertexData":
  47778. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47779. break;
  47780. }
  47781. found = true;
  47782. }
  47783. });
  47784. }
  47785. });
  47786. if (!found) {
  47787. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47788. }
  47789. }
  47790. }
  47791. // Material ?
  47792. if (parsedMesh.materialId) {
  47793. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47794. if (!materialFound && parsedData.multiMaterials) {
  47795. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47796. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47797. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47798. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47799. var subMatId = parsedMultiMaterial.materials[matIndex];
  47800. loadedMaterialsIds.push(subMatId);
  47801. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47802. log += "\n\tMaterial " + mat.toString(fullDetails);
  47803. }
  47804. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47805. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47806. materialFound = true;
  47807. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47808. break;
  47809. }
  47810. }
  47811. }
  47812. if (!materialFound) {
  47813. loadedMaterialsIds.push(parsedMesh.materialId);
  47814. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47815. if (!mat) {
  47816. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47817. }
  47818. else {
  47819. log += "\n\tMaterial " + mat.toString(fullDetails);
  47820. }
  47821. }
  47822. }
  47823. // Skeleton ?
  47824. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  47825. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47826. if (!skeletonAlreadyLoaded) {
  47827. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47828. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47829. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47830. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47831. skeletons.push(skeleton);
  47832. loadedSkeletonsIds.push(parsedSkeleton.id);
  47833. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47834. }
  47835. }
  47836. }
  47837. }
  47838. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47839. meshes.push(mesh);
  47840. log += "\n\tMesh " + mesh.toString(fullDetails);
  47841. }
  47842. }
  47843. // Connecting parents
  47844. var currentMesh;
  47845. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47846. currentMesh = scene.meshes[index];
  47847. if (currentMesh._waitingParentId) {
  47848. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47849. currentMesh._waitingParentId = undefined;
  47850. }
  47851. }
  47852. // freeze and compute world matrix application
  47853. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47854. currentMesh = scene.meshes[index];
  47855. if (currentMesh._waitingFreezeWorldMatrix) {
  47856. currentMesh.freezeWorldMatrix();
  47857. currentMesh._waitingFreezeWorldMatrix = undefined;
  47858. }
  47859. else {
  47860. currentMesh.computeWorldMatrix(true);
  47861. }
  47862. }
  47863. // Particles
  47864. if (parsedData.particleSystems) {
  47865. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47866. var parsedParticleSystem = parsedData.particleSystems[index];
  47867. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47868. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  47869. }
  47870. }
  47871. }
  47872. return true;
  47873. }
  47874. catch (err) {
  47875. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  47876. log = null;
  47877. throw err;
  47878. }
  47879. finally {
  47880. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47881. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47882. }
  47883. }
  47884. },
  47885. load: function (scene, data, rootUrl) {
  47886. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47887. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47888. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47889. // and avoid problems with multiple concurrent .babylon loads.
  47890. var log = "importScene has failed JSON parse";
  47891. try {
  47892. var parsedData = JSON.parse(data);
  47893. log = "";
  47894. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47895. // Scene
  47896. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  47897. scene.autoClear = parsedData.autoClear;
  47898. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  47899. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  47900. if (parsedData.gravity) {
  47901. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  47902. }
  47903. // Fog
  47904. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  47905. scene.fogMode = parsedData.fogMode;
  47906. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  47907. scene.fogStart = parsedData.fogStart;
  47908. scene.fogEnd = parsedData.fogEnd;
  47909. scene.fogDensity = parsedData.fogDensity;
  47910. log += "\tFog mode for scene: ";
  47911. switch (scene.fogMode) {
  47912. // getters not compiling, so using hardcoded
  47913. case 1:
  47914. log += "exp\n";
  47915. break;
  47916. case 2:
  47917. log += "exp2\n";
  47918. break;
  47919. case 3:
  47920. log += "linear\n";
  47921. break;
  47922. }
  47923. }
  47924. //Physics
  47925. if (parsedData.physicsEnabled) {
  47926. var physicsPlugin;
  47927. if (parsedData.physicsEngine === "cannon") {
  47928. physicsPlugin = new BABYLON.CannonJSPlugin();
  47929. }
  47930. else if (parsedData.physicsEngine === "oimo") {
  47931. physicsPlugin = new BABYLON.OimoJSPlugin();
  47932. }
  47933. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  47934. //else - default engine, which is currently oimo
  47935. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  47936. scene.enablePhysics(physicsGravity, physicsPlugin);
  47937. }
  47938. // Metadata
  47939. if (parsedData.metadata !== undefined) {
  47940. scene.metadata = parsedData.metadata;
  47941. }
  47942. //collisions, if defined. otherwise, default is true
  47943. if (parsedData.collisionsEnabled != undefined) {
  47944. scene.collisionsEnabled = parsedData.collisionsEnabled;
  47945. }
  47946. scene.workerCollisions = !!parsedData.workerCollisions;
  47947. var index;
  47948. var cache;
  47949. // Lights
  47950. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  47951. var parsedLight = parsedData.lights[index];
  47952. var light = BABYLON.Light.Parse(parsedLight, scene);
  47953. log += (index === 0 ? "\n\tLights:" : "");
  47954. log += "\n\t\t" + light.toString(fullDetails);
  47955. }
  47956. // Animations
  47957. if (parsedData.animations) {
  47958. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  47959. var parsedAnimation = parsedData.animations[index];
  47960. var animation = BABYLON.Animation.Parse(parsedAnimation);
  47961. scene.animations.push(animation);
  47962. log += (index === 0 ? "\n\tAnimations:" : "");
  47963. log += "\n\t\t" + animation.toString(fullDetails);
  47964. }
  47965. }
  47966. if (parsedData.autoAnimate) {
  47967. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  47968. }
  47969. // Materials
  47970. if (parsedData.materials) {
  47971. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47972. var parsedMaterial = parsedData.materials[index];
  47973. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47974. log += (index === 0 ? "\n\tMaterials:" : "");
  47975. log += "\n\t\t" + mat.toString(fullDetails);
  47976. }
  47977. }
  47978. if (parsedData.multiMaterials) {
  47979. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  47980. var parsedMultiMaterial = parsedData.multiMaterials[index];
  47981. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47982. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  47983. log += "\n\t\t" + mmat.toString(fullDetails);
  47984. }
  47985. }
  47986. // Morph targets
  47987. if (parsedData.morphTargetManagers) {
  47988. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  47989. var managerData = _a[_i];
  47990. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  47991. }
  47992. }
  47993. // Skeletons
  47994. if (parsedData.skeletons) {
  47995. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  47996. var parsedSkeleton = parsedData.skeletons[index];
  47997. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47998. log += (index === 0 ? "\n\tSkeletons:" : "");
  47999. log += "\n\t\t" + skeleton.toString(fullDetails);
  48000. }
  48001. }
  48002. // Geometries
  48003. var geometries = parsedData.geometries;
  48004. if (geometries) {
  48005. // Boxes
  48006. var boxes = geometries.boxes;
  48007. if (boxes) {
  48008. for (index = 0, cache = boxes.length; index < cache; index++) {
  48009. var parsedBox = boxes[index];
  48010. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  48011. }
  48012. }
  48013. // Spheres
  48014. var spheres = geometries.spheres;
  48015. if (spheres) {
  48016. for (index = 0, cache = spheres.length; index < cache; index++) {
  48017. var parsedSphere = spheres[index];
  48018. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  48019. }
  48020. }
  48021. // Cylinders
  48022. var cylinders = geometries.cylinders;
  48023. if (cylinders) {
  48024. for (index = 0, cache = cylinders.length; index < cache; index++) {
  48025. var parsedCylinder = cylinders[index];
  48026. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  48027. }
  48028. }
  48029. // Toruses
  48030. var toruses = geometries.toruses;
  48031. if (toruses) {
  48032. for (index = 0, cache = toruses.length; index < cache; index++) {
  48033. var parsedTorus = toruses[index];
  48034. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  48035. }
  48036. }
  48037. // Grounds
  48038. var grounds = geometries.grounds;
  48039. if (grounds) {
  48040. for (index = 0, cache = grounds.length; index < cache; index++) {
  48041. var parsedGround = grounds[index];
  48042. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  48043. }
  48044. }
  48045. // Planes
  48046. var planes = geometries.planes;
  48047. if (planes) {
  48048. for (index = 0, cache = planes.length; index < cache; index++) {
  48049. var parsedPlane = planes[index];
  48050. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  48051. }
  48052. }
  48053. // TorusKnots
  48054. var torusKnots = geometries.torusKnots;
  48055. if (torusKnots) {
  48056. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  48057. var parsedTorusKnot = torusKnots[index];
  48058. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  48059. }
  48060. }
  48061. // VertexData
  48062. var vertexData = geometries.vertexData;
  48063. if (vertexData) {
  48064. for (index = 0, cache = vertexData.length; index < cache; index++) {
  48065. var parsedVertexData = vertexData[index];
  48066. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  48067. }
  48068. }
  48069. }
  48070. // Meshes
  48071. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48072. var parsedMesh = parsedData.meshes[index];
  48073. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48074. log += (index === 0 ? "\n\tMeshes:" : "");
  48075. log += "\n\t\t" + mesh.toString(fullDetails);
  48076. }
  48077. // Cameras
  48078. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  48079. var parsedCamera = parsedData.cameras[index];
  48080. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  48081. log += (index === 0 ? "\n\tCameras:" : "");
  48082. log += "\n\t\t" + camera.toString(fullDetails);
  48083. }
  48084. if (parsedData.activeCameraID) {
  48085. scene.setActiveCameraByID(parsedData.activeCameraID);
  48086. }
  48087. // Browsing all the graph to connect the dots
  48088. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  48089. var camera = scene.cameras[index];
  48090. if (camera._waitingParentId) {
  48091. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48092. camera._waitingParentId = undefined;
  48093. }
  48094. }
  48095. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48096. var light = scene.lights[index];
  48097. if (light._waitingParentId) {
  48098. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48099. light._waitingParentId = undefined;
  48100. }
  48101. }
  48102. // Sounds
  48103. var loadedSounds = [];
  48104. var loadedSound;
  48105. if (BABYLON.AudioEngine && parsedData.sounds) {
  48106. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48107. var parsedSound = parsedData.sounds[index];
  48108. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48109. if (!parsedSound.url)
  48110. parsedSound.url = parsedSound.name;
  48111. if (!loadedSounds[parsedSound.url]) {
  48112. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48113. loadedSounds[parsedSound.url] = loadedSound;
  48114. }
  48115. else {
  48116. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48117. }
  48118. }
  48119. else {
  48120. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48121. }
  48122. }
  48123. }
  48124. loadedSounds = [];
  48125. // Connect parents & children and parse actions
  48126. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48127. var mesh = scene.meshes[index];
  48128. if (mesh._waitingParentId) {
  48129. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48130. mesh._waitingParentId = undefined;
  48131. }
  48132. if (mesh._waitingActions) {
  48133. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48134. mesh._waitingActions = undefined;
  48135. }
  48136. }
  48137. // freeze world matrix application
  48138. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48139. var currentMesh = scene.meshes[index];
  48140. if (currentMesh._waitingFreezeWorldMatrix) {
  48141. currentMesh.freezeWorldMatrix();
  48142. currentMesh._waitingFreezeWorldMatrix = undefined;
  48143. }
  48144. else {
  48145. currentMesh.computeWorldMatrix(true);
  48146. }
  48147. }
  48148. // Particles Systems
  48149. if (parsedData.particleSystems) {
  48150. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48151. var parsedParticleSystem = parsedData.particleSystems[index];
  48152. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48153. }
  48154. }
  48155. // Lens flares
  48156. if (parsedData.lensFlareSystems) {
  48157. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48158. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48159. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48160. }
  48161. }
  48162. // Shadows
  48163. if (parsedData.shadowGenerators) {
  48164. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48165. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48166. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48167. }
  48168. }
  48169. // Lights exclusions / inclusions
  48170. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48171. var light = scene.lights[index];
  48172. // Excluded check
  48173. if (light._excludedMeshesIds.length > 0) {
  48174. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48175. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48176. if (excludedMesh) {
  48177. light.excludedMeshes.push(excludedMesh);
  48178. }
  48179. }
  48180. light._excludedMeshesIds = [];
  48181. }
  48182. // Included check
  48183. if (light._includedOnlyMeshesIds.length > 0) {
  48184. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48185. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48186. if (includedOnlyMesh) {
  48187. light.includedOnlyMeshes.push(includedOnlyMesh);
  48188. }
  48189. }
  48190. light._includedOnlyMeshesIds = [];
  48191. }
  48192. }
  48193. // Actions (scene)
  48194. if (parsedData.actions) {
  48195. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  48196. }
  48197. // Finish
  48198. return true;
  48199. }
  48200. catch (err) {
  48201. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  48202. log = null;
  48203. throw err;
  48204. }
  48205. finally {
  48206. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48207. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48208. }
  48209. }
  48210. }
  48211. });
  48212. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48213. })(BABYLON || (BABYLON = {}));
  48214. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  48215. var BABYLON;
  48216. (function (BABYLON) {
  48217. var FilesInput = (function () {
  48218. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  48219. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  48220. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  48221. this._engine = p_engine;
  48222. this._canvas = p_canvas;
  48223. this._currentScene = p_scene;
  48224. this._sceneLoadedCallback = p_sceneLoadedCallback;
  48225. this._progressCallback = p_progressCallback;
  48226. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  48227. this._textureLoadingCallback = p_textureLoadingCallback;
  48228. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  48229. }
  48230. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  48231. var _this = this;
  48232. if (p_elementToMonitor) {
  48233. this._elementToMonitor = p_elementToMonitor;
  48234. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  48235. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  48236. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  48237. }
  48238. };
  48239. FilesInput.prototype.renderFunction = function () {
  48240. if (this._additionnalRenderLoopLogicCallback) {
  48241. this._additionnalRenderLoopLogicCallback();
  48242. }
  48243. if (this._currentScene) {
  48244. if (this._textureLoadingCallback) {
  48245. var remaining = this._currentScene.getWaitingItemsCount();
  48246. if (remaining > 0) {
  48247. this._textureLoadingCallback(remaining);
  48248. }
  48249. }
  48250. this._currentScene.render();
  48251. }
  48252. };
  48253. FilesInput.prototype.drag = function (e) {
  48254. e.stopPropagation();
  48255. e.preventDefault();
  48256. };
  48257. FilesInput.prototype.drop = function (eventDrop) {
  48258. eventDrop.stopPropagation();
  48259. eventDrop.preventDefault();
  48260. this.loadFiles(eventDrop);
  48261. };
  48262. FilesInput.prototype.loadFiles = function (event) {
  48263. if (this._startingProcessingFilesCallback)
  48264. this._startingProcessingFilesCallback();
  48265. // Handling data transfer via drag'n'drop
  48266. if (event && event.dataTransfer && event.dataTransfer.files) {
  48267. this._filesToLoad = event.dataTransfer.files;
  48268. }
  48269. // Handling files from input files
  48270. if (event && event.target && event.target.files) {
  48271. this._filesToLoad = event.target.files;
  48272. }
  48273. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48274. for (var i = 0; i < this._filesToLoad.length; i++) {
  48275. var name_1 = this._filesToLoad[i].name.toLowerCase();
  48276. var extension = name_1.split('.').pop();
  48277. var type = this._filesToLoad[i].type;
  48278. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48279. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  48280. this._sceneFileToLoad = this._filesToLoad[i];
  48281. }
  48282. else {
  48283. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  48284. }
  48285. }
  48286. this.reload();
  48287. }
  48288. };
  48289. FilesInput.prototype.reload = function () {
  48290. var _this = this;
  48291. var that = this;
  48292. // If a ".babylon" file has been provided
  48293. if (this._sceneFileToLoad) {
  48294. if (this._currentScene) {
  48295. if (BABYLON.Tools.errorsCount > 0) {
  48296. BABYLON.Tools.ClearLogCache();
  48297. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48298. }
  48299. this._engine.stopRenderLoop();
  48300. this._currentScene.dispose();
  48301. }
  48302. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48303. that._currentScene = newScene;
  48304. // Wait for textures and shaders to be ready
  48305. that._currentScene.executeWhenReady(function () {
  48306. if (that._sceneLoadedCallback) {
  48307. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  48308. }
  48309. that._engine.runRenderLoop(function () { that.renderFunction(); });
  48310. });
  48311. }, function (progress) {
  48312. if (_this._progressCallback) {
  48313. _this._progressCallback(progress);
  48314. }
  48315. });
  48316. }
  48317. else {
  48318. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48319. }
  48320. };
  48321. return FilesInput;
  48322. }());
  48323. FilesInput.FilesToLoad = new Array();
  48324. BABYLON.FilesInput = FilesInput;
  48325. })(BABYLON || (BABYLON = {}));
  48326. //# sourceMappingURL=babylon.filesInput.js.map
  48327. BABYLON.Effect.ShadersStore={"postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#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\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\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\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\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\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(V,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n\n#ifdef REFRACTION\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\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\n#ifdef REFLECTION\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n\n\n\nfloat NdotV=clamp(dot(normalW,viewDirectionW),0.,1.)+0.00001;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\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=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular*=surfaceReflectivityColor;\nfinalSpecular=max(finalSpecular,0.0);\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=surfaceRefractionColor;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\nfinalSpecular*vLightingIntensity.x*vLightingIntensity.w +\n#endif\n#ifdef REFLECTION\nfinalRadiance*vLightingIntensity.z +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=result.a;\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\n\n\n\n\n\n\n\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\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\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ngl_FragColor=color;\n}"};
  48328. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec3 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\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 float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\n\n\n\n\n\nreturn esm;\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\n\n\n\n\n\nreturn esm;\n}\n#endif\n","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\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/(PI*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 reflectance0,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); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\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 fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\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{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\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\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\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}","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.001));\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 reflectance0,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=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*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 reflectance0,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=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*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 reflectance0,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=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 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}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\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,specularEnvironmentR0,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,specularEnvironmentR0,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,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  48329. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  48330. module.exports = BABYLON;
  48331. };